最近做了個有關閱讀的應用,使用了自定義字體,學習了一下這方面的知識。
1.首先是最簡單也普遍的做法,打包內置字符庫文件:
把字體庫文件添加到工程,如font1.ttf添加到工程,然后在工程plist添加一項Fonts provided by application,這是個數組,然后添加key item1,value就是剛才說的font1.ttf,如圖:
那么在工程里就可以直接使用這個字體,直接用
+ (UIFont *)fontWithName:(NSString *)fontName size:(CGFloat)fontSize; 即可。
不過需要注意的是,這個fontName不是文件名,而是里面真正的字體名。如上面的font1.ttf里面的字體是MFQingShu_Noncommercial-Regular,那就直接用
UIFont *font = [UIFont fontWithName:@"MFQingShu_Noncommercial-Regular" size:12];就能去到正確的字體。
2.但是一般來說,字體文件比較大,不該內置,而且如果都用plist預定義的方式,那肯定就沒法覆蓋全,導致用戶不能使用更多自己喜歡的字體。所以應該用代碼讀取字體的方式:
提供字體文件路徑,返回所需要字體:
-(UIFont*)customFontWithPath:(NSString*)path size:(CGFloat)size{ NSURL *fontUrl = [NSURL fileURLWithPath:path]; CGDataProviderRef fontDataProvider = CGDataProviderCreateWithURL((__bridge CFURLRef)fontUrl); CGFontRef fontRef = CGFontCreateWithDataProvider(fontDataProvider); CGDataProviderRelease(fontDataProvider); CTFontManagerRegisterGraphicsFont(fontRef, NULL); NSString *fontName = CFBridgingRelease(CGFontCopyPostScriptName(fontRef)); UIFont *font = [UIFont fontWithName:fontName size:size]; CGFontRelease(fontRef); return font;}
這樣就不需要在plist設定任何東西,只需要得到字體庫文件的路徑,就可以取出對應的字體。
上面的方法對于TTF、OTF的字體都有效,但是對于TTC字體,只取出了一種字體。因為TTC字體是一個相似字體的集合體,一般是字體的組合。所以如果對字體要求比較高,所以可以用下面的方法把所有字體取出來:
-(NSArray*)customFontArrayWithPath:(NSString*)path size:(CGFloat)size{ CFStringRef fontPath = CFStringCreateWithCString(NULL, [path UTF8String], kCFStringEncodingUTF8); CFURLRef fontUrl = CFURLCreateWithFileSystemPath(NULL, fontPath, kCFURLPOSIXPathStyle, 0); CFArrayRef fontArray =CTFontManagerCreateFontDescriptorsFromURL(fontUrl); CTFontManagerRegisterFontsForURL(fontUrl, kCTFontManagerScopeNone, NULL); NSMutableArray *customFontArray = [NSMutableArray array]; for (CFIndex i = 0 ; i < CFArrayGetCount(fontArray); i++){ CTFontDescriptorRef descriptor = CFArrayGetValueAtIndex(fontArray, i); CTFontRef fontRef = CTFontCreateWithFontDescriptor(descriptor, size, NULL); NSString *fontName = CFBridgingRelease(CTFontCopyName(fontRef, kCTFontPostScriptNameKey)); UIFont *font = [UIFont fontWithName:fontName size:size]; [customFontArray addObject:font]; } return customFontArray;}
不過這個方法只支持7.0以上,暫時在7.0以下沒有找到方法。
個人看法,因為ttc里面的字體都比較相似,所以其實使用一個也足以。
附:(字體的介紹)
TTF(TrueTypeFont)是一種字庫名稱。TTF(TrueTypeFont)是Apple公司和Microsoft公司共同推出的字體文件格式,隨著windows的流行,已經變成最常用的一種字體文件表示方式。