美文网首页
iOS动态字体加载及坑

iOS动态字体加载及坑

作者: Realank | 来源:发表于2017-11-17 10:39 被阅读1242次

首先,在iOS中,使用字体文件(网络动态下载或者copy到bundle的方式)并不难,只需要在使用前动态加载就可以:

+ (void) loadCustomFont:(NSString*)fontFileName{
    NSString *fontPath = [[NSBundle MainBundle] pathForResource:fontFileName ofType:nil];
    if (!fontPath) {
        NSLog(@"Failed to load font: %@", fontFileName);
        return;
    }
    NSData *inData = [NSData dataWithContentsOfFile:fontPath];
    CFErrorRef error;
    CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge 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);
}

但是本人就遇到了一个比较奇葩的情况,有一个字体叫做Bebas Neue,有book,regular,bold,thin等类型,但是动态加载以后,虽然通过查询font family啥的,能看到这些类型,可是通过[UIFont fontWithName:@"BebasNeueBook" size:72]获取到的字体,并不是book字体,而是比较粗的字体,这就尴尬了,怎么才能获取到正确的字体呢?StackOverflow无果,自己尝试,发现了一个叫做UIFontDescriptor的东东,这个类可以很详细的描述字体信息,于是曲线救国,通过 [UIFont fontWithDescriptor:[UIFontDescriptor fontDescriptorWithName:@"BebasNeueBook" size:72] size:72]就可以正确加载这个字体了,最后看起来效果棒棒哒。

为了方便使用,我封装了一个方法:

- (UIFont*)loadFontWithName:(NSString*)fontName size:(float)size{
    return [UIFont fontWithDescriptor:[UIFontDescriptor fontDescriptorWithName:fontName size:size] size:size];
}

相关文章

网友评论

      本文标题:iOS动态字体加载及坑

      本文链接:https://www.haomeiwen.com/subject/ynidvxtx.html