iOS

Loading (Encrypted) Custom Fonts in iOS

We talked about adding and using custom font back in 2012.

This is another way now with Core Text framework.

It also helps to load encrypted fonts which could be required by some of the font license.

Loading Custom Font

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#import <CoreText/CoreText.h>

- (void)loadCustomFont {
    NSString *fontPath = [[NSBundle mainBundle] pathForResource:@"JOURNAL" ofType:@"TTF"];
    CFErrorRef error;
    CGDataProviderRef provider = CGDataProviderCreateWithFilename([fontPath UTF8String]);
    CGFontRef font = CGFontCreateWithDataProvider(provider);
    if (! CTFontManagerRegisterGraphicsFont(font, &error)) {
        CFStringRef errorDescription = CFErrorCopyDescription(error);
        NSLog(@"Failed to load font: %@", errorDescription);
        CFRelease(errorDescription);
    }
    CFRelease(font);
    CFRelease(provider);

    // eg. set the font
    self.myFontLabel.font = [UIFont fontWithName:@"Journal" size:20];
}

Loading Encrypted Font

To load encrypted font, use CGDataProviderCreateWithCFData with the decrypted font data:

1
2
3
4
5
NSData *decryptedFontData = ...;
CFErrorRef error;
CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)decryptedFontData);
CGFontRef font = CGFontCreateWithDataProvider(provider);
// ... same code as above ...

Comments