Last active
March 23, 2022 12:33
-
-
Save zwang/7260bfad8a9fa75b61c3 to your computer and use it in GitHub Desktop.
Dynamically load font from a font file in swift in IOS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static func loadFont(fontName: String, baseFolderPath: String) -> Bool { | |
let basePath = baseFolderPath as NSString | |
let fontFilePath = basePath.stringByAppendingPathComponent(fontName) | |
let fontUrl = NSURL(fileURLWithPath: fontFilePath) | |
if let inData = NSData(contentsOfURL: fontUrl) { | |
var error: Unmanaged<CFError>? | |
let cfdata = CFDataCreate(nil, UnsafePointer<UInt8>(inData.bytes), inData.length) | |
if let provider = CGDataProviderCreateWithCFData(cfdata) { | |
if let font = CGFontCreateWithDataProvider(provider) { | |
if (!CTFontManagerRegisterGraphicsFont(font, &error)) { | |
Logger.info("Failed to load font: \(error)") | |
} | |
return true | |
} | |
} | |
} | |
return false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment