我已經知道如何從我的iPhone應用程序加載自定義字體到我的項目here 我想問一下是否有辦法從代碼中做到這一點?我的問題是我的應用程序中有一個資源文件夾,我有一個字體文件名,我們可以稱它爲「myfont.ttf」。iOS中的動態自定義字體加載器
我想要抓住一個TTF文件,並把它從代碼 plist文件,而更重要的是我想知道fontWithName顯示名稱:尺寸:方法。有辦法做到這一點?
我已經知道如何從我的iPhone應用程序加載自定義字體到我的項目here 我想問一下是否有辦法從代碼中做到這一點?我的問題是我的應用程序中有一個資源文件夾,我有一個字體文件名,我們可以稱它爲「myfont.ttf」。iOS中的動態自定義字體加載器
我想要抓住一個TTF文件,並把它從代碼 plist文件,而更重要的是我想知道fontWithName顯示名稱:尺寸:方法。有辦法做到這一點?
是的,你可以。但是你必須用CoreText和/或CoreGraphics來處理很多事情。
有來自Zynga的一個很好的類,它可以幫助你在做這個: https://github.com/zynga/FontLabel
示例項目顯示如何加載的.ttf從包文件,而不使用的.plist並使用應用程序內的這些字體。
該代碼是有效的,從開始就是一個好點。
編輯:以前的方法使用CoreGraphics,這是很好,但使用Core Text要好得多。 我發現這個問題的一個有趣的答案:How can you load a font (TTF) from a file using Core Text?
如果您沒有CoreText框架的經驗,請閱讀official introduction inside the Apple documentation。
這是一個較老的問題,但如果有其他人遇到此問題,則無論如何這都是一種方法。
+ (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);
}
這將加載字體在運行時指定的路徑,那麼你可以像平常一樣使用它,而不必將它添加到plist。
如果您正在下載一個TTF文件,那麼你可以做以下與iOS字體管理器來註冊您的自定義字體,這段代碼也需要照顧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);
}
}
你可以檢查布爾值和註冊和註銷狀態的錯誤。
這工作,它應用字體標籤,但它沒有註冊。 – Durgaprasad 2013-05-04 05:24:52
@ pixelrevision CTFontManagerRegisterGraphicsFont是否會將字體永久註冊到設備 – 2013-05-24 08:39:19
CGFontRef font = CGFontCreateWithDataProvider(provider);應用程序永遠掛在這條線上。 (iOS 10.2) – 2017-01-04 11:31:41