vertically align text in a CATextLayer?

2020-02-05 11:45发布

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 want to center it vertically -- but information about other vertical alignments would also be of interest.

EDIT: I found this, but I can't make it work.

13条回答
forever°为你锁心
2楼-- · 2020-02-05 12:38

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()
    }
}
查看更多
登录 后发表回答