【问题标题】:In iOS, Is it possible to add a font to the app during runtime?在 iOS 中,是否可以在运行时向应用程序添加字体?
【发布时间】:2012-04-06 22:49:44
【问题描述】:

在我的应用程序中,我想让用户下载和使用字体,但我不知道如何动态执行此操作。我知道我们必须在应用程序的Info.plist 文件中指定要使用的字体,但我们无法以编程方式向该 plist 文件添加任何内容。有 zynga 的库,但它是 UILabel 的子类。

请帮忙

【问题讨论】:

  • 我认为动态添加字体是不可能的。
  • itunes.apple.com/in/app/inkpad/id400083414?mt=8 请检查这个应用程序。 Inkpad 这些家伙正在提供此功能。
  • 嗯...我的意思是我认为如果不将 UIFonts 添加到您的应用程序包中,就无法动态管理它们。

标签: iphone objective-c ios uifont


【解决方案1】:

是的,有可能:

/**
 Downloads a `.ttf` file from an URL and creates an UIFont.
 
 - Parameter url: The URL of the `.ttf` file.
 
 - Precondition: The URL Session must be previously configured at ease.
 */
fileprivate func setFont(url: URL) {
    // Download the font file in .ttf format.
    dataTask = urlSession?.dataTask(with: url,
                                    completionHandler: { [weak self] (data, response, error) in
        guard error == nil,
            let data = data,
            (response as? HTTPURLResponse)?.statusCode == 200,
            // Create a Font Descriptor from the raw data.
            let ctFontDescriptor = CTFontManagerCreateFontDescriptorFromData(data as CFData) else {
                // Error during the download of the .ttf file.
                self?.error()
                return
        }
        // Create CTFont from the Font Descriptor and convert it to UIFont.
        let font: UIFont = CTFontCreateWithFontDescriptor(ctFontDescriptor, 0.0, nil) as UIFont
        // Do whatever you want with the UIFont :)
        self?.success(font: font)
    })
    dataTask?.resume()
}

使用此代码,您可以从 Internet 下载包含字体的 .ttf 文件(您可以从任何其他来源获取该文件)并将其用作 UIFont。

【讨论】:

  • git repo 链接似乎不存在了。
【解决方案2】:

您可以使用CGFontCreateWithDataProvider(),后跟CTFontCreateWithGraphicsFont()。然后你就有了一个 CTFont,你可以使用 Core Text 来绘制它。

据我所知,如果您的应用程序包中没有该字体并使用 Info.plist 方法(即不下载它)或使用私有 API,则无法从自定义字体中获取 UIFont。

【讨论】:

  • This answer 推测您可能可以转换为 UIFont,但他说他没有尝试过代码。
  • 谢谢艾米,我现在正在看。
  • 你可以在 UIFont 中使用它,根据 Marco Arment 的说法:marco.org/2012/12/21/ios-dynamic-font-loading
  • CTFontCreateWithGraphicsFont() 这个方法永远挂起。 (iOS 10.2)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-28
  • 1970-01-01
  • 2019-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多