在我的应用程序中,我想让用户下载和使用字体,但我不知道如何动态地实现这一点。我知道我们必须在应用程序的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()
}
CGFontCreateWithDataProvider()
接着使用CTFontCreateWithGraphicsFont()
来创建一个CTFont,然后你可以使用Core Text进行绘制。实际上,在运行时下载和注册字体是可能的,您需要将字体下载到本地文件夹,然后可以使用CTFontManagerRegisterFontsForURL
或CTFontManagerRegisterGraphicsFont
进行注册。
我发现使用CTFontManagerRegisterFontsForURL
似乎可以加载具有多个样式的TTF,而使用CGDataProvider
与CTFontManagerRegisterGraphicsFont
只能加载一个。
请记住,URL需要是内部URL,而不是http URL。
var unmanagedError: Unmanaged<CFError>?
if CTFontManagerRegisterFontsForURL(url as CFURL, .process, &unmanagedErrorT) == true {
// SUCCESS CODE
} else {
// ERROR CODE
unmanagedError?.release()
}