下载apple支持的字体到

从mac字体册中查找字体的PostScript 名称作为fontName进行字体下载:

下载apple支持的字体到_第1张图片
2028D541-5D80-4F9B-9A22-B7DEEF71906A.png

代码是swift3.0,每种字体只需要下载一次,下次就不会需要下载了,所以不用担心每次都下载消耗流量和时间的问题

func downloadFont(fontName: String, fontSize: CGFloat, downloading: @escaping (Double) -> Void, completion: @escaping (UIFont) -> Void){
        var font = UIFont.init(name: fontName, size: fontSize);
        if font != nil {
            // 字体已经下载过
            if (font?.fontName.compare(fontName) == .orderedSame) || (font?.familyName.compare(fontName) == .orderedSame) {
                completion(font!)
            } else {
                print("创建字体出错了")
            }
        } else {
            // 下载字体
            let attrs = NSMutableDictionary.init(dictionary: [kCTFontNameAttribute : fontName])
            let desc = CTFontDescriptorCreateWithAttributes(attrs)
            let descs = [desc]
            var errorFlag: Bool = false
            CTFontDescriptorMatchFontDescriptorsWithProgressHandler(descs as CFArray, nil, { (state, parameter) -> Bool in
                let progressValue = ((parameter as NSDictionary)[kCTFontDescriptorMatchingPercentage] as AnyObject).doubleValue
                switch state {
                case CTFontDescriptorMatchingState.didBegin:
                    print("字体已经匹配")
                case CTFontDescriptorMatchingState.didFinish:
                    if !errorFlag {
                        print("字体\(fontName)下载完成")
                        DispatchQueue.main.async {
                            font = UIFont.init(name: fontName, size: fontSize);
                            if let aFont = font {
                                completion(aFont)
                            }
                        }
                    }
                case CTFontDescriptorMatchingState.willBeginDownloading:
                    print("字体开始下载")
                case CTFontDescriptorMatchingState.didFinishDownloading:
                    print("字体下载完成")
                case CTFontDescriptorMatchingState.downloading:
                    downloading(progressValue!)
                case CTFontDescriptorMatchingState.didFailWithError:
                    let error = (parameter as NSDictionary)[kCTFontDescriptorMatchingError]
                    var errorMessage: String? = nil
                    if error != nil {
                        errorMessage = error.debugDescription
                    } else {
                        errorMessage = "ERROR MESSAGE IS NOT AVALABLE!"
                    }
                    print("error: "+errorMessage!)
                    errorFlag = true
                default:
                    break
                }
                return true
            })
        }
    }

你可能感兴趣的:(下载apple支持的字体到)