How to dynamically load a font under iOS. (for real)

Ark-kun picture Ark-kun · Dec 27, 2012 · Viewed 11.6k times · Source

I've seen this question asked and answered numerous times, but I haven't seen a real answer. The common "solutions" are:

  • Add the font to the application bundle and register it in the info.plist file.
  • Use a custom font parsing and rendering library (like the Zynga's FontLabel).
  • It cannot be done.

So the question is: How to dynamically load a font under iOS? Loading the font "dynamically" means loading any given font which is not known at the time of the app's compilation.

Answer

Ark-kun picture Ark-kun · Dec 27, 2012

Fonts can easily be dynamically loaded from any location or any byte stream. See the article here: 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);
  • You don't have to put the font in your bundle.
  • You don't have to explicitly register the font in your info.plist.

See also: 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