如何平滑完成无限动画

问题描述 投票:0回答:1

我有无穷大CABasicAnimation,它实际上通过增大和减小比例来模拟脉动:

scaleAnimation.fromValue = 0.5
scaleAnimation.toValue = 1.0
scaleAnimation.duration = 0.8

scaleAnimation.autoreverses = true
scaleAnimation.repeatCount = .greatestFiniteMagnitude
scaleAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)

我想在toValue中平稳地停止播放此动画。换句话说,我要允许当前的动画循环完成,但不要重复。有没有一个很好的方法来做到这一点?我对冻结当前动画,将其删除并创建具有时间偏移的新动画有一些想法,但是也许有更好的方法?

swift core-animation
1个回答
1
投票

有一种干净的标准方法,尽管如果您不了解它,这实际上很棘手:

  1. 首先要做的是将图层的比例设置为其presentationLayer的比例。

  2. 然后在图层上调用removeAllAnimations

  3. 现在进行快速动画制作,将图层的比例设置为1。

这是一个可能的实现(为获得额外的荣誉,我想我们可以调整快速动画的持续时间以匹配当前缩放比例,但在这里我不介意这样做):

@IBAction func doStop(_ sender: Any) {
    let lay = v.layer
    lay.transform = lay.presentation()!.transform
    lay.removeAllAnimations()
    CATransaction.flush()
    lay.transform = CATransform3DIdentity
    let scaleAnimation = CABasicAnimation(keyPath: "transform")
    scaleAnimation.duration = 0.4
    scaleAnimation.timingFunction = CAMediaTimingFunction(name: .easeOut)
    lay.add(scaleAnimation, forKey: nil)
}

结果:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.