菜鸟教程小白 发表于 2022-12-11 18:01:19

ios - 如何从文件(而不是 info.plist)在 iOS 应用程序中加载自定义字体?


                                            <p><p>我想知道在我的控件(UILabel、UIButton 等)中使用字体之前,是否可以从文件(例如 Internet URL)中将字体加载到我的 iOS 应用程序中。我已经知道预打包它并在 info.plist 中引用的常用技术,但我正在寻找一个不太静态的选项....可行吗?</p>

<p>谢谢!</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>是的。这是绝对可能的。您需要查看 <code>CTFontManagerRegisterGraphicsFont</code>。</p>

<p>这是一个用法示例:</p>

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

<p>Swift 版本:</p>

<pre><code>func loadFont(_ name: String) -&gt; Bool {
    let bundle = Bundle(for: self)
    guard let fontPath = bundle.path(forResource: name, ofType: &#34;ttf&#34;),
      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&lt;CFError&gt;?

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

    return true
}
</code></pre>

<p> <a href="https://marco.org/2012/12/21/ios-dynamic-font-loading" rel="noreferrer noopener nofollow">https://marco.org/2012/12/21/ios-dynamic-font-loading</a> </p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 如何从文件(而不是 info.plist)在 iOS 应用程序中加载自定义字体?,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/40508041/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/40508041/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 如何从文件(而不是 info.plist)在 iOS 应用程序中加载自定义字体?