最近作了個有關閱讀的應用,使用了自定義字體,學習了一下這方面的知識。windows
1.首先是最簡單也廣泛的作法,打包內置字符庫文件:數組
把字體庫文件添加到工程,如font1.ttf添加到工程,而後在工程plist添加一項Fonts provided by application,這是個數組,而後添加key item1,value就是剛纔說的font1.ttf,如圖:app
那麼在工程裏就能夠直接使用這個字體,直接用ide
+ (UIFont *)fontWithName:(NSString *)fontName size:(CGFloat)fontSize; 便可。學習
不過須要注意的是,這個fontName不是文件名,而是裏面真正的字體名。如上面的font1.ttf裏面的字體是MFQingShu_Noncommercial-Regular,那就直接用字體
UIFont *font = [UIFont fontWithName:@"MFQingShu_Noncommercial-Regular" size:12];就能去到正確的字體。spa
2.可是通常來講,字體文件比較大,不應內置,並且若是都用plist預約義的方式,那確定就無法覆蓋全,致使用戶不能使用更多本身喜歡的字體。因此應該用代碼讀取字體的方式:code
提供字體文件路徑,返回所須要字體:blog
-(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設定任何東西,只須要獲得字體庫文件的路徑,就能夠取出對應的字體。ip
上面的方法對於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的流行,已經變成最經常使用的一種字體文件表示方式。