How can I rotate a CATextLayer properly in Swift?

517 Views Asked by At

I'm currently facing an issue that when rotating a CATextLayer the frame size would be transformed unexpectedly at the same time. I expect the text can be rotated at some angle without changing its frame size. If anyone could enlighten me about this, thanks in advance.

What I have tried:

var someAngle: CGFloat = 0 {
    didSet {
        drawText()
    }
}

func drawText() {

    for layer in someView.layer.sublayers ?? [] where layer is CATextLayer {
        layer.removeFromSuperlayer()
    }

    let textLayer = CATextLayer()
    textLayer.fontSize = 26
    textLayer.backgroundColor = UIColor.lightGray.cgColor
    textLayer.string = "Hello world"
    textLayer.alignmentMode = .center

    textLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    textLayer.transform = CATransform3DMakeRotation(someAngle, 0.0, 0.0, 1.0)

    let textSize = calculateTextSize(text: "Hello world", font: UIFont.systemFont(ofSize: 26))
    let origin = CGPoint(x: someView.bounds.midX - textSize.width/2, y: someView.bounds.midY - textSize.height/2)
    textLayer.frame = CGRect(origin: origin, size: textSize)

    someView.layer.addSublayer(textLayer)
}

However, the result looks like this:

enter image description here

And my expectation is similar to this: enter image description here

1

There are 1 best solutions below

1
Joey Zhang On

solved this by adding a textLayer property outside the function.

var textLayer = CATextLayer()