如何为CATextLayer宽度设置动画并使文本平滑生长

时间:2019-05-23 20:07:03

标签: ios swift animation catextlayer

我在UIView中有一个CATextLayer。

我为UIView框架设置动画以便与

一起生长
UIView.animate(withDuration: 3.0, delay: 0, options: .beginFromCurrentState, animations: anim, completion: nil)

我也更改了CATextLayer的框架而没有动画,因为frame属性不可动画。 我用下一个代码为CATextLayer边界和fontSize属性设置动画:

let textBoundsAnim = CABasicAnimation(keyPath: "bounds")
textBoundsAnim.toValue = CGRect(x: 0, y: 0, width: self.contentView.frame.width - 70, height: textRect.height)
textBoundsAnim.fromValue = textLayer.bounds
textBoundsAnim.duration = 3.0
textBoundsAnim.fillMode = .forwards
textBoundsAnim.isRemovedOnCompletion = false
textBoundsAnim.delegate = self
textLayer.add(textBoundsAnim, forKey: "boundsChange")

let textFontAnim = CABasicAnimation(keyPath: "fontSize")
textFontAnim.fromValue = translatedTextLayer.fontSize
textFontAnim.toValue = 21
textFontAnim.duration = 5.0
textFontAnim.fillMode = .forwards
textFontAnim.isRemovedOnCompletion = false
textFontAnim.delegate = self
textLayer.add(textFontAnim, forKey: "fontSizeChange")

动画的最终状态看起来不错,但是在动画处理过程中,文本不可见。

我认为文本的大小是根据帧大小计算的,并且文本会立即从视图帧中消失。

enter image description here

如何随着父视图的增加而同时增加文本的动画

更新: 我认为出现文本动画的问题是因为计算句子的长度与帧有关。在文档中,请注意,不能对帧进行动画处理。 我有一个想法,当父视图更改其大小时,可以在父视图的layoutSubviews()方法中更改框架文本。 示例:

CATransaction.begin()
if let animation = layer.animation(forKey: "position") {
    CATransaction.setAnimationDuration(animation.duration)

    CATransaction.setAnimationTimingFunction(animation.timingFunction)
} else {
    CATransaction.disableActions()
}

        textLayer.frame = parentView.bounds

CATransaction.commit()

此解决方案正确吗?

0 个答案:

没有答案