+ (UIFont *)yq_cloudFontWithFilePath:(NSString *)filePath size:(CGFloat)size
{
UIFont *systemFont = [UIFont systemFontOfSize:size];
if (![[NSFileManager defaultManager]fileExistsAtPath:filePath]) {
return systemFont;
}
CFURLRef fontURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (__bridge CFStringRef)filePath, kCFURLPOSIXPathStyle, false);
CGDataProviderRef dataProvider = CGDataProviderCreateWithURL(fontURL);
if(!dataProvider) return systemFont;
CFRelease(fontURL);
CGFontRef graphicsFont = CGFontCreateWithDataProvider(dataProvider);
CGDataProviderRelease(dataProvider);
if (!graphicsFont) return systemFont;
CTFontRef smallFont = CTFontCreateWithGraphicsFont(graphicsFont, size, NULL, NULL);
CGFontRelease(graphicsFont);
UIFont *returnFont = (__bridge UIFont *)smallFont;
CFRelease(smallFont);
return returnFont;
}
另一种如下:
+ (UIFont *)yq_cloudFontWithFilePath:(NSString *)filePath size:(CGFloat)size
{
UIFont *sysFont = [UIFont systemFontOfSize:size];
if (![[NSFileManager defaultManager]fileExistsAtPath:filePath]) {
return sysFont;
}
CFURLRef fontURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (__bridge CFStringRef)filePath, kCFURLPOSIXPathStyle, false);
CGDataProviderRef dataProvider = CGDataProviderCreateWithURL(fontURL);
if(!dataProvider) return sysFont;
CFRelease(fontURL);
CGFontRef fontRef = CGFontCreateWithDataProvider(dataProvider);
CGDataProviderRelease(dataProvider);
if (!fontRef) return sysFont;
CFErrorRef errorRef;
CFStringRef fontName = CGFontCopyPostScriptName(fontRef);
NSString *fontNameCopy = (__bridge NSString *)(fontName);
if ([[UIFont familyNames] containsObject:fontNameCopy]) {
UIFont *font = [self fontWithName:(__bridge NSString *)(fontName) size:size];
if (fontName) CFRelease(fontName);
CGFontRelease(fontRef);
return font;
} else {
BOOL suc = CTFontManagerRegisterGraphicsFont(fontRef, &errorRef);
if (!suc) {
CGFontRelease(fontRef);
return sysFont;
} else {
UIFont *font = [self fontWithName:(__bridge NSString *)(fontName) size:size];
if (fontName) CFRelease(fontName);
CGFontRelease(fontRef);
return font;
}
}
}