使用CAKeyframeAnimation可以实现Layer按照特定path上移动的效果,比如说一个圆、一个矩形等。
如果需要path上循环移动,怎么做呢?
当然是设置repeatCount,想循环多少次就设置多少次,如果是无限循环呢,就设置为NSNotFound
ok,看效果是循环起来了。
But,有点问题,为什么每次循环完一圈后,启动下一圈时会卡顿一下呢?
原来是需要设置这个参数calculationMode,设置为什么呢? kCAAnimationPaced or kCAAnimationCubicPaced
不过需要注意下Api的说明,设置这两个模式,keyTimes和timingFunctions将会被忽略。
/* The "calculation mode". Possible values are `discrete', `linear',
* `paced', `cubic' and `cubicPaced'. Defaults to `linear'. When set to
* `paced' or `cubicPaced' the `keyTimes' and `timingFunctions'
* properties of the animation are ignored and calculated implicitly. */
有关CoreAnimation的更多用法,可以看Demo 地址
上代码:
@IBAction func ca6(_ sender: Any) {
let path = CGMutablePath()
path.addEllipse(in: CGRect(x: 100, y: 200, width: 100, height: 100))
let frameAnimation = frameAnimationWithPath(keyPath: "position", path: path as CGPath)
runRepeatAniamtion(animation: frameAnimation)
}
func frameAnimationWithPath(keyPath: String, path: CGPath) -> CAAnimation {
let animation = CAKeyframeAnimation(keyPath: keyPath)
animation.path = path
animation.calculationMode = kCAAnimationPaced
return animation
}
func runRepeatAniamtion(duration: Double = 2, repeatCount: Float = 100, animation: CAAnimation...) -> Void {
let animateGroup = CAAnimationGroup()
animateGroup.animations = animation
animateGroup.duration = duration
animateGroup.repeatCount = repeatCount
hatImage.layer.add(animateGroup, forKey: nil)
}