2
我想知道是否有可能從我的iOS應用程序中加載字體從文件(比如說,互聯網URL),然後在我的控件(UILabel,UIButton等)中使用它。我已經知道通常的預包裝方法,並且在info.plist中引用,但我正在尋找一個不太靜態的選項....可行嗎?如何從iOS文件(不是來自info.plist)加載自定義字體?
謝謝!
我想知道是否有可能從我的iOS應用程序中加載字體從文件(比如說,互聯網URL),然後在我的控件(UILabel,UIButton等)中使用它。我已經知道通常的預包裝方法,並且在info.plist中引用,但我正在尋找一個不太靜態的選項....可行嗎?如何從iOS文件(不是來自info.plist)加載自定義字體?
謝謝!
是的。這絕對有可能。你需要看看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);
斯威夫特版本:
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
}