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;
}
}
-(void)downloadFont:(NSString *)fontStr
{
if ([self isFontDownloaded:fontStr]) {
//已经下载过,发送通知 ,UI修改字体
[[NSUserDefaults standardUserDefaults] setObject:fontStr forKey:@"fontnamekey"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"fontnamekey" object:self];
return;
}
//创建一个字典承装 字体的name postscript
NSMutableDictionary *attrs = [NSMutableDictionary dictionaryWithObjectsAndKeys:fontStr,kCTFontNameAttribute, nil];
//创建一个字体描述对象
CTFontDescriptorRef desc = CTFontDescriptorCreateWithAttributes((__bridge CFDictionaryRef)attrs);
//字体描述对象放到数组中
NSMutableArray *descs = [NSMutableArray arrayWithCapacity:0];
[descs addObject:(__bridge id)desc];
CFRelease(desc);
__block BOOL errorDuringDownload = NO;
//准备好字体描述对象,开始下载字体
CTFontDescriptorMatchFontDescriptorsWithProgressHandler( (__bridge CFArrayRef)descs, NULL, ^bool(CTFontDescriptorMatchingState state, CFDictionaryRef _Nonnull progressParameter) {
double progressValue = [[(__bridge NSDictionary *)progressParameter objectForKey:(id)kCTFontDescriptorMatchingPercentage] doubleValue];
if (state == kCTFontDescriptorMatchingDidBegin) {
NSLog(@" 字体已经开始匹配 ");
} else if (state == kCTFontDescriptorMatchingDidFinish) {
if (!errorDuringDownload) {
NSLog(@" 字体匹配完成 ", fontStr);
}
} else if (state == kCTFontDescriptorMatchingWillBeginDownloading) {
NSLog(@" 字体开始下载 ");
} else if (state == kCTFontDescriptorMatchingDidFinishDownloading) {
NSLog(@" 字体下载完成 ");
dispatch_async( dispatch_get_main_queue(), ^ {
// 可以在这里修改 UI 控件的字体
[[NSUserDefaults standardUserDefaults] setObject:fontStr forKey:kFontNameKey];
[[NSNotificationCenter defaultCenter] postNotificationName:kNotificationFontName object:self];
});
} else if (state == kCTFontDescriptorMatchingDownloading) {
NSLog(@" 下载进度 %.0f%% ", progressValue);
} else if (state == kCTFontDescriptorMatchingDidFailWithError) {
NSError *error = [(__bridge NSDictionary *)progressParameter objectForKey:(id)kCTFontDescriptorMatchingError];
if (error != nil) {
self->_errorMessage = [error description];
} else {
self->_errorMessage = @"ERROR MESSAGE IS NOT AVAILABLE!";
}
// 设置标志
errorDuringDownload = YES;
NSLog(@" 下载错误: %@", self->_errorMessage);
}
return (BOOL)YES;
});
}
参考链接:http://blog.devtang.com/2013/08/11/ios-asian-font-download-introduction/
注意:打包报错: Incompatible block pointer types passing 'BOOL (^)(CTFontDescriptorMatch,使用这个方法:
CTFontDescriptorMatchFontDescriptorsWithProgressHandler( (__bridge CFArrayRef)descs, NULL, ^bool(CTFontDescriptorMatchingState state, CFDictionaryRef _Nonnull progressParameter)
网友评论