user3532505
user3532505

Reputation: 419

Animate `CATextLayer` font-size from bottom left

is it possible to animate the font-size of a CATextLayer, starting from bottom left?

I am able to animate the CATextLayer with the following code, but it is always starting from top-left:

let fontSizeAnimation = CABasicAnimation(keyPath: "fontSize")
fontSizeAnimation.toValue = 24.0
fontSizeAnimation.duration = 2
fontSizeAnimation.fillMode = .forwards
fontSizeAnimation.isRemovedOnCompletion = false

textLayer.add(fontSizeAnimation, forKey: "fontSizeAnimation")

Upvotes: 0

Views: 124

Answers (1)

dengST30
dengST30

Reputation: 4037

You need to use custom CATextLayer

class BottomTxtLayer: CATextLayer {

    // Key point: The changes come solely in recalculating the vertical position of the text represented by the yDiff
    override func draw(in context: CGContext) {
        let height = bounds.size.height
        let fontSize = fontSize
        let yDiff = (height-fontSize) - fontSize/10

        context.saveGState()
        // Use -yDiff when in non-flipped coordinates
        context.translateBy(x: 0, y: yDiff)
        super.draw(in: context)
        context.restoreGState()
    }
}

example added

class ViewController: UIViewController {

    let myTextLayer = BottomTxtLayer()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
       
        myTextLayer.alignmentMode = .left
        myTextLayer.string = "吴钩霜雪明"
        myTextLayer.backgroundColor = UIColor.blue.cgColor
        myTextLayer.foregroundColor = UIColor.cyan.cgColor
        myTextLayer.frame = CGRect(x: 100, y: 100, width: 200, height: 200)
        view.layer.addSublayer(myTextLayer)
        
    }

    
    
    @IBAction func animate(_ sender: Any) {
        
        let fontSizeAnimation = CABasicAnimation(keyPath: "fontSize")
        fontSizeAnimation.toValue = 24.0
        fontSizeAnimation.duration = 2
        fontSizeAnimation.fillMode = .forwards
        fontSizeAnimation.isRemovedOnCompletion = false
        myTextLayer.add(fontSizeAnimation, forKey: "fontSizeAnimation")
    }
}

Upvotes: 1

Related Questions