Loading Fonts

有兩種在應用中加載字體的方式。第一種方法是更改應用的plist文件, 僅適用于程序編寫者;另一種load fonts dynamically,也適用于框架編寫者。

Load fonts within an app

參考來源:http://stackoverflow.com/questions/21737788/custom-fonts-in-ios-7
First of all I'm assuming that SpriteKit doesn't make any difference.

  1. You need your font in .otf or .ttf copied to your project. For example in Supporting Files.
  2. You need to edit .plist file. Add "Fonts provided by application" key into your plist and in Item 0 copy the exact filename of the font you copied to your Supporting files WITH extension. For example: "JosefinSansStd-Light_0.otf"
  3. Make sure that the font you imported to your app is being packed into app itself. Do that by selecting your Target, then Build Phases, then Copy Bundle Resources. If you don't see your font in there, drag it from Supporting Files.

Finally, you would like to list all your fonts when the app starts just to see useable name for your font. You will do that with this little piece of code:

NSArray *fontFamilies = [UIFont familyNames];
for (int i = 0; i < [fontFamilies count]; i++) {
  NSString *fontFamily = [fontFamilies objectAtIndex:i];
  NSArray *fontNames = [UIFont fontNamesForFamilyName:   [fontFamilies objectAtIndex:i]];
  NSLog (@"%@: %@", fontFamily, fontNames);
}

Search for your font in printed results, for example, I would search for "Josefin" and I would see that actual font name is "JosefinSansStd-Light". After that you only need to use that font by:

UIFont *customFont = [UIFont fontWithName:@"JosefinSansStd-Light" size:20];

In iOS8 you add your fonts directly to the project and they are visible in the interface builder. Modify your code to account for this but programmatically setting font for iOS7 and selecting it in xCode6 interface builder. PS. Interface builder in xCode6 gives you the correct font name that you can copy-paste into the code below.

#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)

if(SYSTEM_VERSION_LESS_THAN(@"8.0")) {
  UIFont *customFont = [UIFont fontWithName:@"OpenSans-Light" size:32];
  self.registerLabel.font = customFont;  
}

Load fonts dynamically

參考來源:http://www.marco.org/2012/12/21/ios-dynamic-font-loading

- (void)loadFont {
  NSData *inData = /* your decrypted font-file data */;
  CFErrorRef error;

  CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)inData);
  CGFontRef font = CGFontCreateWithDataProvider(provider);

  if (! CTFontManagerRegisterGraphicsFont(font, &error)) {
  CFStringRef errorDescription = CFErrorCopyDescription(error)
  NSLog(@"Failed to load font: %@", errorDescription);
  CFRelease(errorDescription);
  }

  CFRelease(font);
  CFRelease(provider);
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容