大家都发现在很多阅读类APP中都有很多字体风格,如果自己实现比较的麻烦,需要打包字体库内嵌到项目中,字体库又大,大多数情况下吃力不讨好;如果想做一个个性点APP,想要实现不同风格字体,有没有的能够简单的实现呢?
今天发现苹果官方的文档显示IOS6支持应用内字体库直接动态下载:
苹果官方动态下载链接:Demo工程
1、判断是否下载过该字体
- (BOOL)isFontDownloaded:(NSString *)fontName {
UIFont* aFont = [UIFont fontWithName:fontName size:12.0];
if (aFont && ([aFont.fontName compare:fontName] == NSOrderedSame
|| [aFont.familyName compare:fontName] == NSOrderedSame)) {
return YES;
} else {
return NO;
}
}
2、下载指定字体名称字体库
// 用字体的PostScript名字创建一个Dictionary
NSMutableDictionary *attrs = [NSMutableDictionary dictionaryWithObjectsAndKeys:fontName, kCTFontNameAttribute, nil];
// 创建一个字体描述对象CTFontDescriptorRef
CTFontDescriptorRef desc = CTFontDescriptorCreateWithAttributes((__bridge CFDictionaryRef)attrs);
// 将字体描述对象放到一个NSMutableArray中
NSMutableArray *descs = [NSMutableArray arrayWithCapacity:0];
[descs addObject:(__bridge id)desc];
CFRelease(desc);
__block BOOL errorDuringDownload = NO;
CTFontDescriptorMatchFontDescriptorsWithProgressHandler( (__bridge CFArrayRef)descs, NULL, ^(CTFontDescriptorMatchingState state, CFDictionaryRef progressParameter) {
double progressValue = [[(__bridge NSDictionary *)progressParameter objectForKey:(id)kCTFontDescriptorMatchingPercentage] doubleValue];
if (state == kCTFontDescriptorMatchingDidBegin) {
NSLog(@"字体已经匹配");
} else if (state == kCTFontDescriptorMatchingDidFinish) {
if (!errorDuringDownload) {
NSLog(@"字体%@ 下载完成", fontName);
}
} else if (state == kCTFontDescriptorMatchingWillBeginDownloading) {
NSLog(@"字体开始下载");
} else if (state == kCTFontDescriptorMatchingDidFinishDownloading) {
NSLog(@"字体下载完成");
dispatch_async( dispatch_get_main_queue(), ^ {
// 可以在这里修改UI控件的字体
});
} else if (state == kCTFontDescriptorMatchingDownloading) {
NSLog(@"下载进度 %.0f%% ", progressValue);
} else if (state == kCTFontDescriptorMatchingDidFailWithError) {
NSError *error = [(__bridge NSDictionary *)progressParameter objectForKey:(id)kCTFontDescriptorMatchingError];
if (error != nil) {
_errorMessage = [error description];
} else {
_errorMessage = @"ERROR MESSAGE IS NOT AVAILABLE!";
}
// 设置标志
errorDuringDownload = YES;
NSLog(@"下载错误: %@", _errorMessage);
}
return (BOOL)YES;
});
3、下载完更显字体UI,如上图所示!
kCTFontDescriptorMatchingDidFinishDownloading
在该方法中通过GCD (dispatch_async( dispatch_get_main_queue(), ^ {})更显UI界面,或者通过广播,KVO等都可以实现整个程序的字体风格的变更;
下载的子图库存在: ****Simulator/6.0/Library/Assets/com_apple_MobileAsset_Font/
简单的记录下:^_^!