前面iOS 开发动画 View Animation讲的都是基于 UIView 的系统封装的高级 API。CoreAnimation 是在 Layer层上操作添加动画,可以做出更复杂的动画。
UIView 和 CALayer 的区别:
(1) UIView 是继承自 UIResponse,可以处理响应事件,CALayer 是继承自 NSObject,只负责内容的创建和绘制。
(2) UIView 负责内容的管理,CALayer 负责内容的绘制。
(3) UIView 的位置属性frame
bounds
center
而 CALayer除了这些属性之外还有anchorPoint
position
(4) CALayer 可以实现 UIView 很多无法实现的功能
注意:CoreAnimation 的动画执行过程都是在后台执行的,不会阻塞主线程。
CABaseAnimation
常用的属性
animation.keyPath // 动画操作的属性
animation.toValue // 属性值的最终值
animation.duration // 动画执行的时间
animation.fillMode // 执行后的状态
animation.isRemovedOnCompletion // 动画执行后要不要删除
动画的类型
1.平移动画: position transform.translation.x transform.translation.y transform.translation.z
2.旋转动画: transform.rotation transform.rotation.x transform.rotation transform.rotation.y
3.缩放动画: bounds transform.scale transform.scale.x transform.scale.y
4.颜色动画:backgroundColor borderColor
5.淡入淡出:opacity
6.高级动画:(圆角)cornerRadius (边框) borderWidth (阴影)shadowOffse
CABaseAnimation选择其一 keyPath 作为例子
阴影动画
override func viewDidLoad() {
super.viewDidLoad()
redView.layer.shadowColor = UIColor.black.cgColor
redView.layer.shadowOpacity = 0.5
let animation = CABasicAnimation()
animation.keyPath = "shadowOffset"
animation.toValue = NSValue(cgPoint: CGPoint(x: 10, y: 10))
animation.duration = 2.0
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = false
redView.layer.add(animation, forKey: nil)
}
CAKeyframeAnimation
新增几个属性
path:运动的路线
values: 关键帧(如果设置了 path,values 是被忽略的)
keyTimes:为对应的关键帧指定的时间点,范围是0~1的
// 1.创建动画对象
CAKeyframeAnimation * anim = [CAKeyframeAnimation animation];
// 2.设置动画属性
anim.keyPath = @"position";
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddEllipseInRect(path, NULL, CGRectMake(100, 100, 200, 200));
anim.path = path;
CGPathRelease(path);
// 动画的执行节奏
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
anim.duration = 2.0f;
anim.removedOnCompletion = NO;
anim.fillMode = kCAFillModeForwards;
anim.delegate = self;
[self.redView.layer addAnimation:anim forKey:nil];