Vir*_*ani 5 iphone objective-c uifont ios
在我的应用程序中,我想让用户下载并使用字体,但我不知道如何动态地执行此操作。我知道我们必须指定要在应用程序文件中使用的字体Info.plist,但我们无法以编程方式向该 plist 文件添加任何内容。有 zynga 的库,但它是UILabel.
请帮忙
对的,这是可能的:
/**
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()
}
Run Code Online (Sandbox Code Playgroud)
使用此代码,您可以从 Internet 下载包含字体的.ttf文件(您可以从任何其他来源获取该文件)并将其用作 UIFont。
您可以使用CGFontCreateWithDataProvider()后跟CTFontCreateWithGraphicsFont(). 然后你就会有一个 CTFont,你可以使用 Core Text 来绘制它。
据我所知,如果您的应用程序包中没有该字体并使用 Info.plist 方法(即不下载它)或使用私有 API,则无法从自定义字体中获取 UIFont。