vertically align text in a CATextLayer?

后端 未结 15 1341
时光说笑
时光说笑 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:21

    Swift 3 version for regular and attributed strings.

    class ECATextLayer: CATextLayer {
        override open func draw(in ctx: CGContext) {
            let yDiff: CGFloat
            let fontSize: CGFloat
            let height = self.bounds.height
    
            if let attributedString = self.string as? NSAttributedString {
                fontSize = attributedString.size().height
                yDiff = (height-fontSize)/2
            } else {
                fontSize = self.fontSize
                yDiff = (height-fontSize)/2 - fontSize/10
            }
    
            ctx.saveGState()
            ctx.translateBy(x: 0.0, y: yDiff)
            super.draw(in: ctx)
            ctx.restoreGState()
        }
    }
    

提交回复
热议问题