在iOS中,是否可以在运行时向应用程序添加字体?

5
在我的应用程序中,我想让用户下载和使用字体,但我不知道如何动态地实现这一点。我知道我们必须在应用程序的Info.plist文件中指定要使用的字体,但我们无法以编程方式向该plist文件添加任何内容。有Zynga的库,但它是UILabel的子类。请帮忙。

我认为动态添加字体是不可能的。 - Giuseppe Garassino
请检查此应用程序:http://itunes.apple.com/in/app/inkpad/id400083414?mt=8。Inkpad这些人提供此功能。 - Virat Naithani
嗯...我的意思是,我认为在不将UIFont添加到应用程序包中的情况下动态管理它们是不可能的。 - Giuseppe Garassino
3个回答

5

是的,这是可能的:

/**
 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()
}

使用这段代码,你可以从互联网上下载一个包含字体的.ttf文件(你也可以从其他来源获得该文件),并将其用作UIFont。

1
该 Git 仓库链接似乎已经不存在了。 - RTXGamer

3
你可以使用CGFontCreateWithDataProvider()接着使用CTFontCreateWithGraphicsFont()来创建一个CTFont,然后你可以使用Core Text进行绘制。
据我所知,除了在应用程序包中拥有字体并使用Info.plist方法(即不下载字体),或者使用私有API,没有其他方法可以从自定义字体中获取UIFont。

这个答案猜测你可能能够将其转换为UIFont,但他说他没有尝试过这段代码。 - Amy Worrall
谢谢Amy,我现在正在看它。 - Virat Naithani
2
你可以根据Marco Arment的建议在UIFont中使用它:http://www.marco.org/2012/12/21/ios-dynamic-font-loading - Zev Eisenberg
CTFontCreateWithGraphicsFont()这个方法一直卡住不动。(iOS 10.2) - dev gr
如果您在使用具有多种样式的ttf时遇到问题,请查看我在另一篇帖子中的答案:https://dev59.com/p2HVa4cB1Zd3GeqPqtVn#72287153 - Pau Ballada

0

实际上,在运行时下载和注册字体是可能的,您需要将字体下载到本地文件夹,然后可以使用CTFontManagerRegisterFontsForURLCTFontManagerRegisterGraphicsFont进行注册。

我发现使用CTFontManagerRegisterFontsForURL似乎可以加载具有多个样式的TTF,而使用CGDataProviderCTFontManagerRegisterGraphicsFont只能加载一个。

请记住,URL需要是内部URL,而不是http URL。

    var unmanagedError: Unmanaged<CFError>?
    if CTFontManagerRegisterFontsForURL(url as CFURL, .process, &unmanagedErrorT) == true {
         // SUCCESS CODE
    } else {
         // ERROR CODE
         unmanagedError?.release()
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接