如何在iOS下动态加载字体.(真的)

Ark*_*kun 14 fonts dynamic truetype ios

我已经看过这个问题并且多次回答,但我没有看到真正的答案.常见的"解决方案"是:

  • 将字体添加到应用程序包并将其注册到info.plist文件中.
  • 使用自定义字体解析和渲染库(如Zynga的FontLabel).
  • 它无法完成.

所以问题是:如何在iOS下动态加载字体? "动态"加载字体意味着加载在应用程序编译时未知的任何给定字体.

Ark*_*kun 24

可以从任何位置或任何字节流轻松地动态加载字体.请参阅此处的文章:http://www.marco.org/2012/12/21/ios-dynamic-font-loading

NSData *inData = /* your 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);
Run Code Online (Sandbox Code Playgroud)
  • 您不必将字体放入捆绑包中.
  • 您不必在info.plist中明确注册该字体.

另请参阅:https: //developer.apple.com/library/mac/#documentation/Carbon/Reference/CoreText_FontManager_Ref/Reference/reference.html#//apple_ref/doc/uid/TP40008278

https://developer.apple.com/library/mac/#documentation/GraphicsImaging/Reference/CGFont/Reference/reference.html#//apple_ref/c/func/CGFontCreateWithDataProvider


sha*_*all 9

Marco最近发表的一篇名为" 动态加载iOS字体"的文章.

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);
Run Code Online (Sandbox Code Playgroud)

  • 这是一个非常有趣的情况.我发现了Marco的帖子并发布了相同的代码作为对SO的一系列问题的答案.但后来我认为创建一个自我回答的问题可能会更好,这样答案就更容易被发现了.然后主持人用我自己的问题用相同的代码删除了我自己的答案=( (2认同)