iOS6之后的系统,苹果官方支持动态下载官方提供的中文字体。这样不仅可以避免版权问题,也可以减少项目的体积。下面就简单的介绍字体库的动态下载。
获取字体的PostScript###
MAC系统自带的字体集中,具体位置如下图。
字体PostScript位置
1、判断字体是否已存在###
示例代码如下:
+ (BOOL)isFontDownloaded:(NSString *)postScriptName{
UIFont *font = [UIFont fontWithName:postScriptName size:12.0];
if (font && ([font.fontName compare:postScriptName] == NSOrderedSame || [font.familyName compare:postScriptName] == NSOrderedSame)) {
return YES;
}
return NO;
}
2、开始下载字体###
示例代码如下:
+ (void)downloadFontWithPostScriptName:(NSString *)postScriptName{
if ([self isFontDownloaded:postScriptName]) {
return;
}
NSMutableDictionary *attrsDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:postScriptName,kCTFontNameAttribute, nil];
CTFontDescriptorRef descriptor = CTFontDescriptorCreateWithAttributes((__bridge CFDictionaryRef)attrsDictionary);
NSMutableArray *descriptorArray = [NSMutableArray array];
[descriptorArray addObject:(__bridge id)descriptor];
CFRelease(descriptor);
__block BOOL errorDuringDownload = NO;
CTFontDescriptorMatchFontDescriptorsWithProgressHandler((__bridge CFArrayRef)descriptorArray, 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(@"字体%@下载完成",postScriptName);
}
}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];
NSString *errorMesage = [NSString string];
if (error != nil) {
errorMesage = [error description];
} else {
errorMesage = @"ERROR MESSAGE IS NOT AVAILABLE!";
}
// 设置下载失败标志
errorDuringDownload = YES;
NSLog(@"下载错误:%@",errorMesage);
}
return (bool)YES;
});
}
网友评论