iOS中的dynamic自定义字体加载器

我已经知道如何加载自定义字体到我的项目在iPhone应用程序从这里我想问是否有办法从代码做到这一点? 我的问题是,我有一个资源文件夹在我的应用程序,我有一个字体文件名称,让我们称之为“ myfont.ttf ”。

我想抓住一个ttf文件,并把它从代码放到plist文件中,还有什么我想知道fontWithName:size: method的显示名称。 有办法做到这一点?

是的你可以。 但是你必须用CoreText和/或CoreGraphics工作很多。

Zynga有一个很好的课程可以帮助你做到这一点: https : //github.com/zynga/FontLabel

示例项目显示如何从软件包加载.ttf文件而不使用.plist,并在应用程序内使用这些字体。

该代码是有效的,从一开始就是一个好点。

编辑:以前的方法使用CoreGraphics,这是好的,但使用核心文本好多了。 我发现这个问题有一个有趣的答案: 如何从文件使用核心文本加载字体(TTF)?

如果您没有CoreText框架的经验,请阅读Apple文档中的官方介绍 。

这是一个较老的问题,但如果有其他人遇到这种情况,这是一种方法。

+ (void)loadFontAtPath:(NSString*)path{ NSData *data = [[NSFileManager defaultManager] contentsAtPath:path]; if(data == nil){ NSLog(@"Failed to load font. Data at path is null"); return; } CFErrorRef error; CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)data); CGFontRef font = CGFontCreateWithDataProvider(provider); if(!CTFontManagerRegisterGraphicsFont(font, &error)){ CFStringRef errorDescription = CFErrorCopyDescription(error); NSLog(@"Failed to load font: %@", errorDescription); CFRelease(errorDescription); } CFRelease(font); CFRelease(provider); } 

这将加载字体在运行时指定的path,那么你可以像平常一样使用它,而不必将它添加到plist。

如果您正在下载一个TTF文件,那么您可以使用iOS Font Manager注册您的自定义字体,这段代码还会处理TTF文件更新(字体更新):

  +(void)registerFontsAtPath:(NSString *)ttfFilePath { NSFileManager * fileManager = [NSFileManager defaultManager]; if ([fileManager fileExistsAtPath:ttfFilePath] == YES) { [UIFont familyNames];//This is here for a bug where font registration API hangs for forever. //In case of TTF file update : Fonts are already registered, first de-register them from Font Manager CFErrorRef cfDe_RegisterError; bool fontsDeregistered = CTFontManagerUnregisterFontsForURL((__bridge CFURLRef)[NSURL fileURLWithPath:ttfFilePath], kCTFontManagerScopeNone, &cfDe_RegisterError); //finally register the fonts with Font Manager, CFErrorRef cfRegisterError; bool fontsRegistered= CTFontManagerRegisterFontsForURL((__bridge CFURLRef)[NSURL fileURLWithPath:ttfFilePath], kCTFontManagerScopeNone, &cfRegisterError); } } 

您可以检查布尔和错误的注册和注销状态。