我有一个CAKeyframeAnimation
动画,我想用repeatCount = HUGE_VALF
永远重复一遍。动画的持续时间是2秒,但我想在每个周期之前暂停3秒。
我能想到的唯一两种方法是:
让整个动画持续5秒,并添加额外的keyTimes和值,以便在5s动画的最后3s内获得我正在寻找的暂停。这感觉有点哈哈。
让动画只重复一次,然后添加类似performSelector:afterDelay:2
的内容再次运行动画,依此类推。这也很脏。也意味着我需要每5秒拨一次addAnimation:
,我不确定它在性能方面是否是最佳的。
我可能会遗失另一种选择吗?这两种方法中哪一种比另一种更好?
答案 0 :(得分:118)
通过转储Apple MKUserLocationView
的动画,我能够看到他们是如何做到的。事实证明这就是CAAnimationGroup
的用途。通过将2秒动画封装到5秒动画组中,您最终会得到2秒动画,然后是3秒延迟:
CAAnimationGroup *animationGroup = [CAAnimationGroup animation];
animationGroup.duration = 5;
animationGroup.repeatCount = INFINITY;
CAMediaTimingFunction *easeOut = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
CABasicAnimation *pulseAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale.xy"];
pulseAnimation.fromValue = @0.0;
pulseAnimation.toValue = @1.0;
pulseAnimation.duration = 2;
pulseAnimation.timingFunction = easeOut;
animationGroup.animations = @[pulseAnimation];
[ringImageView.layer addAnimation:animationGroup forKey:@"pulse"];
答案 1 :(得分:7)
samvermette在Swift 3中的回答:
let animationGroup = CAAnimationGroup()
animationGroup.duration = 5;
animationGroup.repeatCount = .infinity
let easeOut = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
let pulseAnimation = CABasicAnimation(keyPath: "transform.scale.xy")
pulseAnimation.fromValue = 0
pulseAnimation.toValue = 1.0
pulseAnimation.duration = 2
pulseAnimation.timingFunction = easeOut
animationGroup.animations = [pulseAnimation]
ringImageView.layer.add(animationGroup, forKey: "pulse")
答案 2 :(得分:0)
Tested on Swift 4.2
Just implement the following extension and then you can get a nice pulse Animation on Any UI component
//MARK:- Pulse animation
extension UIView {
func applyPulse(_ apply: Bool = true) {
if apply {
let animation = CABasicAnimation(keyPath: "transform.scale")
animation.toValue = 1.5
animation.duration = 0.8
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
animation.autoreverses = true
animation.repeatCount = Float.infinity
self.layer.add(animation, forKey: "pulsing")
} else {
self.layer.removeAnimation(forKey: "pulsing")
}
}
}
Usase:
To start
yourUiComponent.applyPulse()
To Stop
yourUiComponent.applyPulse(false)