前面iOS 開發(fā)動畫 View Animation講的都是基于 UIView 的系統(tǒng)封裝的高級 API。CoreAnimation 是在 Layer層上操作添加動畫,可以做出更復(fù)雜的動畫。
UIView 和 CALayer 的區(qū)別:
(1) UIView 是繼承自 UIResponse,可以處理響應(yīng)事件,CALayer 是繼承自 NSObject,只負(fù)責(zé)內(nèi)容的創(chuàng)建和繪制。
(2) UIView 負(fù)責(zé)內(nèi)容的管理,CALayer 負(fù)責(zé)內(nèi)容的繪制。
(3) UIView 的位置屬性frameboundscenter而 CALayer除了這些屬性之外還有anchorPointposition
(4) CALayer 可以實(shí)現(xiàn) UIView 很多無法實(shí)現(xiàn)的功能
注意:CoreAnimation 的動畫執(zhí)行過程都是在后臺執(zhí)行的,不會阻塞主線程。
CABaseAnimation
常用的屬性
animation.keyPath // 動畫操作的屬性
animation.toValue // 屬性值的最終值
animation.duration // 動畫執(zhí)行的時(shí)間
animation.fillMode // 執(zhí)行后的狀態(tài)
animation.isRemovedOnCompletion // 動畫執(zhí)行后要不要刪除
動畫的類型
1.平移動畫: position transform.translation.x transform.translation.y transform.translation.z
2.旋轉(zhuǎn)動畫: 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
新增幾個(gè)屬性
path:運(yùn)動的路線
values: 關(guān)鍵幀(如果設(shè)置了 path,values 是被忽略的)
keyTimes:為對應(yīng)的關(guān)鍵幀指定的時(shí)間點(diǎn),范圍是0~1的
// 1.創(chuàng)建動畫對象
CAKeyframeAnimation * anim = [CAKeyframeAnimation animation];
// 2.設(shè)置動畫屬性
anim.keyPath = @"position";
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddEllipseInRect(path, NULL, CGRectMake(100, 100, 200, 200));
anim.path = path;
CGPathRelease(path);
// 動畫的執(zhí)行節(jié)奏
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];