vertically align text in a CATextLayer?

后端 未结 15 1337
时光说笑
时光说笑 2020-12-10 10:41

I am working on a CATextLayer that I want to use in both Mac and iOS. Can I control the vertical alignment of the text within the layer?

In this particular case, I

15条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 11:13

    The code for Swift 3, based on code @iamktothed

    If you use an attributed string for setting font properties, than you can use function size() from NSAttributedString to calculate height of string. I think this code also resolve the problems described by @Enix

    class LCTextLayer: CATextLayer {
    
        override init() {
            super.init()
        }
    
        override init(layer: Any) {
            super.init(layer: layer)
        }
    
        required init(coder aDecoder: NSCoder) {
            super.init(layer: aDecoder)
        }
    
        override open func draw(in ctx: CGContext) {
    
            if let attributedString = self.string as? NSAttributedString {
    
                let height = self.bounds.size.height
                let stringSize = attributedString.size()
                let yDiff = (height - stringSize.height) / 2
    
                ctx.saveGState()
                ctx.translateBy(x: 0.0, y: yDiff)
                super.draw(in: ctx)
                ctx.restoreGState()
            }
        }
    }
    

提交回复
热议问题