how to load a custom font in iOS app from a file (not from info.plist)?

谁都会走 提交于 2021-02-19 05:42:27

问题


I am wondering if it's possible to load a font from a file (say, internet URL) into my iOS app, before using it in my controls (UILabel, UIButton, etc). I already know the usual technique of pre-packaging it and referencing inside info.plist, but I'm looking for a less static option.... doable?

Thanks!


回答1:


Yes. It's absolutely possible. You need to look at CTFontManagerRegisterGraphicsFont.

Here’s a usage example:

NSData *inData = /* your decrypted font-file data */;
CFErrorRef error;
CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)inData);
CGFontRef font = CGFontCreateWithDataProvider(provider);
if (! CTFontManagerRegisterGraphicsFont(font, &error)) {
    CFStringRef errorDescription = CFErrorCopyDescription(error)
    NSLog(@"Failed to load font: %@", errorDescription);
    CFRelease(errorDescription);
}
CFRelease(font);
CFRelease(provider);

Swift version:

func loadFont(_ name: String) -> Bool {
    let bundle = Bundle(for: self)
    guard let fontPath = bundle.path(forResource: name, ofType: "ttf"),
        let data = try? Data(contentsOf: URL(fileURLWithPath: fontPath)),
        let provider = CGDataProvider(data: data as CFData)
    else {
        return false
    }

    let font = CGFont(provider)
    var error: Unmanaged<CFError>?

    let success = CTFontManagerRegisterGraphicsFont(font, &error)
    if !success {
        print("Error loading font. Font is possibly already registered.")
        return false
    }

    return true
}

https://marco.org/2012/12/21/ios-dynamic-font-loading



来源:https://stackoverflow.com/questions/40508041/how-to-load-a-custom-font-in-ios-app-from-a-file-not-from-info-plist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!