let animation = CABasicAnimation(keyPath:"transform.rotation.z")
属性
fromValue:开始值
toValue:结束值(绝对值)
byValue:结束值(相对值)
duration:动画的时间
repeatCount:重复次数 (永久的话值设置为:HUGE)
beginTime:指定动画开始时间。延迟执行的话,设置为:CACurrentMediaTime() + 秒数
timingFunction:设定动画的速度变化
autoreverses:动画结束时是否执行逆动画
keyPath
通过设置keyPath的值实现不同的动画效果
keyPath值 | 类型描述 | 值范围 |
---|---|---|
transform.scale | 比例变化 | 0 ~ 1 |
transform.scale.x | 宽比例变化 | 0 ~ 1 |
transform.scale.y | 宽比例变化 | 0 ~ 1 |
transform.rotation.x | 围绕X轴旋转 | 0 ~ 2*M_PI |
transform.rotation.y | 围绕Y轴旋转 | 0 ~ 2*M_PI |
transform.rotation.z | 围绕Z轴旋转 | 0 ~ 2*M_PI |
cornerRadius | 圆角变化 | 0 ~ 2*MAX(width,height) |
backgroundColor | 颜色变化,透明度不变 | AnyColor.cgColor |
opacity | 透明度变化 | 0 ~ 1 |
bounds | 大小变化,中心不变 | CGRect |
position | 中心变化 | CGPoint |
position.x | 中心X变化 | CGFloat |
position.y | 中心Y变化 | CGFloat |
contents | 内容变化 如ImageView.image | image.cgImage |
borderWidth | 边框宽 | 0 ~ |
添加动画
为Layer添加设置完成的动画,可以给Key指定任意名字。
myView.layer.add(animation, forKey: "animation")
动画结束后回到初始状态的现象的解决方法
用CABasicAnimation执行动画,在动画结束后会回归动画开始前的状态。想要解决的话,必须设置“removedOnCompletion”和“fillMode”这两个属性。
animation.isRemovedOnCompletion = false
animation.fillMode = .forwards
捕获动画开始和结束
CAAnimationDelegate
animation.delegate = self
func animationDidStart(_ anim: CAAnimation) {
PrintLog(message: "动画开始")
}
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
PrintLog(message: "动画结束")
}
动画组
使用CAAnimationGroup类进行复数动画的组合
//动画1
let animation1 = CABasicAnimation(keyPath:"transform.translation.x")
animation1.fromValue = 0
animation1.toValue = Double.pi * 2
//动画2
let animation2 = CABasicAnimation(keyPath:"transform.rotation.y")
animation2.fromValue = 0
animation2.toValue = Double.pi * 2
//动画组
let group = CAAnimationGroup()
group.duration = 2
group.repeatCount = HUGE
group.animations = [animation1, animation2]
myView.layer.add(group, forKey: "group")
移除动画
//移除所有的动画
myView.layer.removeAllAnimations()
//移除指定动画
self.bigImagView.layer.removeAnimation(forKey: "key")
网友评论