提供字体文件路径,返回所需要字体:
-(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;
}