iOS 系统字体下载

2018-10-26  本文已影响2545人  LearningCoding

开发中,低版本系统打开 PDF、Word 可能会出现乱码情况,很大的原因是低版本没有该字体造成的。

1、在 mac 上找到字体 PostScript 名称

Find 搜索字体册


781540352115_.pic.jpg

找到对应的字体 PostScript


791540352161_.pic_hd.jpg

注意:你可能会有一个疑问,为什么不把字体文件拖到项目中,在 plist 文件中添加,不就不用下载了吗?
右键点击该字体,在 Find 中显示,我们发现该字体太大了,放到项目中反而得不偿失。
再者,苹果系统字体现在后是统一保存到系统文件下,所有 App 公用,也就是说,如果有其他 App 下载过该字体,咱们的也可以直接使用了。


811540538357_.pic_hd.jpg

2、话不多说,直接上代码

新建系统字体下载管理类

@implementation FontNameManager
+ (instancetype)shareManager {
    static FontNameManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[FontNameManager alloc] init];
    });
    return manager;
}

- (void)asynchronouslySetFontName:(NSString *)fontName
{
    UIFont* aFont = [UIFont fontWithName:fontName size:12.0];
    // If the font is already downloaded
    if (aFont && ([aFont.fontName compare:fontName] == NSOrderedSame || [aFont.familyName compare:fontName] == NSOrderedSame)) {
        // 已经有改字体
        return;
    }
    
    // Create a dictionary with the font's PostScript name.
    NSMutableDictionary *attrs = [NSMutableDictionary dictionaryWithObjectsAndKeys:fontName, kCTFontNameAttribute, nil];
    
    // Create a new font descriptor reference from the attributes dictionary.
    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,  ^(CTFontDescriptorMatchingState state, CFDictionaryRef progressParameter) {
        
        //NSLog( @"state %d - %@", state, progressParameter);
        
        double progressValue = [[(__bridge NSDictionary *)progressParameter objectForKey:(id)kCTFontDescriptorMatchingPercentage] doubleValue];
        
        if (state == kCTFontDescriptorMatchingDidBegin) {
            NSLog(@" 字体匹配成功 ");
        } else if (state == kCTFontDescriptorMatchingDidFinish) {
            dispatch_async( dispatch_get_main_queue(), ^ {
                
                // Log the font URL in the console
                CTFontRef fontRef = CTFontCreateWithName((__bridge CFStringRef)fontName, 0., NULL);
                CFStringRef fontURL = CTFontCopyAttribute(fontRef, kCTFontURLAttribute);
                NSLog(@"%@", (__bridge NSURL*)(fontURL));
                CFRelease(fontURL);
                CFRelease(fontRef);
                
                if (!errorDuringDownload) {
                    NSLog(@" 字体 %@ 下载完成 ", fontName);
                }
            });
        } else if (state == kCTFontDescriptorMatchingWillBeginDownloading) {
            NSLog(@" 字体开始下载 ");
        } else if (state == kCTFontDescriptorMatchingDidFinishDownloading) {
            NSLog(@" 字体下载完成 ");
            dispatch_async( dispatch_get_main_queue(), ^ {
            });
        } else if (state == kCTFontDescriptorMatchingDownloading) {
            NSLog(@" 下载进度 %.0f%% ", progressValue);
        } else if (state == kCTFontDescriptorMatchingDidFailWithError) {
            // An error has occurred.
            // Get the error message
            NSError *error = [(__bridge NSDictionary *)progressParameter objectForKey:(id)kCTFontDescriptorMatchingError];
            NSString *errorMessage = @"";
            if (error != nil) {
                errorMessage = [error description];
            } else {
                errorMessage = @"ERROR MESSAGE IS NOT AVAILABLE!";
            }
            // Set our flag
            errorDuringDownload = YES;
            
            dispatch_async( dispatch_get_main_queue(), ^ {
                NSLog(@"Download error: %@", errorMessage);
            });
        }
        return (bool)YES;
    });
}

在合适的位置,下载字体:

// 下载 黑体-简 细体
[[FontNameManager shareManager] asynchronouslySetFontName:@"STHeitiSC-Light"];

参考:https://developer.apple.com/library/archive/samplecode/DownloadFont/Listings/DownloadFont_ViewController_m.html

上一篇 下一篇

猜你喜欢

热点阅读