CATextLayer.font
属性是一个不透明的 CFTypeRef
。有没有办法将该引用转换为 UIFont
?我不介意它是否返回可选的 UIFont。
最佳答案
我刚刚编写了以下应该处理的扩展:CTFont
、CGFont
、字符串名称或 UIFont
:
extension CATextLayer {
public var typeFace:UIFont? {
let name:String
switch font {
case let ctFont as CTFont :
// If you assign a UIFont to CATextLayer.font
// it is implicitly converted to CTFont,
// so this case will be called.
guard let _name = CTFontCopyName(ctFont, kCTFontPostScriptNameKey) else {
return nil
}
name = _name as NSString as String
case let cgFont as CGFont :
guard let _name = cgFont.postScriptName else {
return nil
}
name = _name as NSString as String
case let string as NSString :
name = string as String
case let string as String :
name = string
default:
return nil
}
return UIFont(name:name, size:fontSize)
}
}
附带说明一下,我发现文档中的这条评论不准确:
In iOS, you cannot assign a UIFont object to this property.
根据我的测试,我能够在 CATextLayer.font
上设置一个 UIFont
,它似乎工作正常。
编辑
事实证明,当您将 UIFont
分配给 CATextLayer.font
时,它会在幕后转换为 CTFont
,因此为了返回 UIFont
有必要将 CTFont
转换为 UIFont
(我的代码就是这样做的)。简单地转换为 UIFont
是行不通的。
关于ios - 将 CATextLayer 字体转换为 UIFont,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47922763/