Reputation: 419
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
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