2016-11-09 6 views
2

コントロール(UILabel、UIButtonなど)で使用する前に、iOSアプリケーションにファイル(インターネットURLなど)からフォントを読み込むことができるかどうかは疑問です。私はすでにそれを事前にパッケージ化しinfo.plistを参照する通常のテクニックを知っていますが、静的ではないオプションを探しています。iOSアプリでカスタムフォントを読み込む方法(info.plistではなく)

ありがとうございます!

答えて

0

はい。絶対に可能です。あなたはCTFontManagerRegisterGraphicsFontを見る必要があります。

ここでの使用例です:

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); 

スウィフトバージョン:

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

関連する問題