react-native icon indicating copy to clipboard operation
react-native copied to clipboard

Can't user custom font in iOS.

Open rainer-liao opened this issue 10 years ago • 6 comments

Can't use custom font in React Native iOS. My font family name is "Impact". In RCTConvert.m

+ (UIFont *)UIFont:(UIFont *)font withFamily:(id)family
              size:(id)size weight:(id)weight style:(id)style
   scaleMultiplier:(CGFloat)scaleMultiplier
  UIFont *bestMatch = font;
  CGFloat closestWeight = INFINITY;
  for (NSString *name in [UIFont fontNamesForFamilyName:familyName]) {
    UIFont *match = [UIFont fontWithName:name size:fontSize];
    if (isItalic == RCTFontIsItalic(match) &&
        isCondensed == RCTFontIsCondensed(match)) {
      CGFloat testWeight = RCTWeightOfFont(match);
      if (ABS(testWeight - fontWeight) < ABS(closestWeight - fontWeight)) {
        bestMatch = match;
        closestWeight = testWeight;
      }
    }
  }
return bestMatch;

I find when I use font family "Impact", the code

isItalic == RCTFontIsItalic(match) &&
        isCondensed == RCTFontIsCondensed(match)

return false so bestMatch return nil.

I also find other custom font families work fine. Just "Impact" don't.

rainer-liao avatar May 19 '16 08:05 rainer-liao

Yeah, seems kind of clear that a match is a better match than none. I guess I see where the issue lies in the code, but it would be helpful if you can prepare a small app that reproduces the problem for testing purposes. Maybe there’s a built-in font that also suffers from this problem? (Would be even better to not have to include a custom font.)

alloy avatar May 19 '16 10:05 alloy

I did a quick test over all the built-in fonts (and Impact) and these are the fonts that return nil for bestMatch:

  • Avenir Next Condensed
  • Party LET
  • Savoye Let
  • Zapfino
  • Impact (custom font)

However, you can still render those builtin fonts by setting the fontFamily to the full font name. eg. SavoyeLetPlain or AvenirNextCondensed-Heavy however, this won't work for Impact as Impact is the font name as well as the font family name, as they "both" return nil

rogchap avatar May 23 '16 03:05 rogchap

Oops.. I missed one (added to list above): Zapfino This built-in font suffers the exact problem.

Would this be enough to fix the problem:

// If we still don't have a match at least return the first font in the fontFamily
  if (!bestMatch) {
    NSArray *names = [UIFont fontNamesForFamilyName:familyName];
    if (names.count > 0) {
      bestMatch = [UIFont fontWithName:names[0] size:fontSize];
    }
  }

rogchap avatar May 23 '16 03:05 rogchap

That seems reasonable to me. The alternative is just not finding a font, right? Would you be interested in sending a pull request for this?

lacker avatar Oct 26 '16 06:10 lacker

Hey @lacker Sure I can put a PR together.

rogchap avatar Oct 26 '16 22:10 rogchap

Closing because this seems to be resolved

ericvicenti avatar Jan 09 '17 10:01 ericvicenti