我想知道在我的控件(UILabel、UIButton 等)中使用字体之前,是否可以从文件(例如 Internet URL)中将字体加载到我的 iOS 应用程序中。我已经知道预打包它并在 info.plist 中引用的常用技术,但我正在寻找一个不太静态的选项....可行吗?
谢谢!
Best Answer-推荐答案 strong>
是的。这是绝对可能的。您需要查看 CTFontManagerRegisterGraphicsFont 。
这是一个用法示例:
NSData *inData = /* your decrypted font-file data */;
CFErrorRef error;
CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)inData);
CGFontRef font = CGFontCreateWithDataProvider(provider);
if (! CTFontManagerRegisterGraphicsFont(font, &error)) {
CFStringRef errorDescription = CFErrorCopyDescription(error)
NSLog(@"Failed to load font: %@", errorDescription);
CFRelease(errorDescription);
}
CFRelease(font);
CFRelease(provider);
Swift 版本:
func loadFont(_ name: String) -> Bool {
let bundle = Bundle(for: self)
guard let fontPath = bundle.path(forResource: name, ofType: "ttf"),
let data = try? Data(contentsOf: URL(fileURLWithPath: fontPath)),
let provider = CGDataProvider(data: data as CFData)
else {
return false
}
let font = CGFont(provider)
var error: Unmanaged<CFError>?
let success = CTFontManagerRegisterGraphicsFont(font, &error)
if !success {
print("Error loading font. Font is possibly already registered.")
return false
}
return true
}
https://marco.org/2012/12/21/ios-dynamic-font-loading
关于ios - 如何从文件(而不是 info.plist)在 iOS 应用程序中加载自定义字体?,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/40508041/
|