【问题标题】:Convert CATextLayer font to UIFont将 CATextLayer 字体转换为 UIFont
【发布时间】:2017-12-21 20:43:34
【问题描述】:

CATextLayer.font 属性是不透明的CFTypeRef。有没有办法将该引用转换为UIFont?我不介意它是否返回一个可选的 UIFont。

【问题讨论】:

  • 根据文档,它是May be either a CTFont, a CGFont, an instance of NSFont (macOS only), or a string naming the font。那么stackoverflow.com/questions/6714858/…stackoverflow.com/questions/9205709/… 等等?根据类型,函数等效名称应该在 Swift 中可用。 stackoverflow.com/questions/3471964/…获取类型?
  • 既然你创建了文本层并配置了它,你怎么会不知道你分配了什么字体呢?
  • 简单。这是通用框架的一部分,我在几个地方使用不同字体的文本层。事实上,我下面的答案是需要getset 的协议实现的修改版本。不做任何假设。

标签: ios swift cocoa


【解决方案1】:

我刚刚写了以下应该处理的扩展:CTFontCGFont、字符串名称或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)
    }
}

附带说明,我发现文档中的这条评论不准确:

在 iOS 中,您不能将 UIFont 对象分配给此属性。

根据我的测试,我能够在CATextLayer.font 上设置UIFont,它似乎工作正常。


编辑

事实证明,当您将 UIFont 分配给 CATextLayer.font 时,它会在幕后转换为 CTFont,因此为了使 UIFont 退出,有必要从 CTFont 转换为 @ 987654332@(我的代码就是这样)。简单地转换为 UIFont 是行不通的。

【讨论】:

    【解决方案2】:

    你可以这样做,

    let font : UIFont = layer.font as! UIFont
    

    希望对你有帮助

    【讨论】:

    • 这没关系,只是首先分配了一个 UIFont,否则它将失败。附带说明一下,我不会强制转换,因为我的返回类型是UIFont?,它可以只是return self.font as? UIFont
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-06
    • 2014-11-20
    • 2012-03-01
    • 2020-05-19
    • 2012-04-04
    • 2011-08-23
    • 1970-01-01
    相关资源
    最近更新 更多