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

问题描述 投票:2回答:2

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

请帮助

iphone objective-c ios uifont
2个回答
3
投票

您可以使用CGFontCreateWithDataProvider(),然后使用CTFontCreateWithGraphicsFont()。然后,您将获得一个CTFont,可以使用Core Text进行绘制。

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


0
投票

是,有可能:

/**
 Downloads a `.ttf` file from an URL and changes label's font.

 - 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。

GitHub repository

enter image description here


0
投票

是,有可能:

/**
 Downloads a `.ttf` file from an URL and changes label's font.

 - 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。

GitHub repo

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.