Core Animation 是直接作用在 CALayer上的(並非 UIview 上)非常強大的跨 Mac OS X 和 iOS 平臺的動畫處理 API, Core Animation 的動畫執行過程都是在後臺操作的, 不會阻塞主線程.
1. Core Animation 繼承結構:
2. 基本用法:
使用步驟類似於手勢識別:
> 創建動畫對象
> 設置動畫屬性
> 把動畫對象添加到某個 CALayer 對象上
> 需要停止動畫: 可以調用 remove 方法移除動畫
3. 動畫類型:
> 基本動畫(CABasicAnimation): 設定某個屬性從某個值到某個值, 實現基本動畫
是 CAPropectyAnimation 的子類
1) 屬性說明:
keyPath: 要改變的屬性名稱(傳字符串)
fromValue: keyPath相應屬性的初始值
toValue: keyPath相應屬性的結束值
2) 動畫過程說明:
隨着動畫的進行, 在長度爲 duration 的持續時間內, ketPath 相應屬性的值從 fromValue 漸漸地變爲 toValue
keyPath 內容是 CALayer 的可動畫 Animatable 屬性
如果 fillMode = kCAFillModeForwards 同時 removedOnComletion = NO, 那麼在動畫執行完畢後, 圖層會保持顯示動畫執行後的狀態. 但實質上, 圖層的屬性值還是動畫執行前的初始值, 並沒有真正被改變
> 屬性動畫: 設定某個屬性的值, 可以實現屬性動畫
> 關鍵幀動畫(CAKeyframeAnimation): 設定某個屬性的值從某個值到某個值, 再到某個值. 積累的關鍵值挨着器做
也是 CAPropectyAnimation 的子類, 與 CABasicAnimation 的區別是:
CABasicAnimation 只能從一個數值(fromValue)變到另一個數值(toValue), 而 CAKeyframeAnimation 會使用一個 NSArray 保存這些數值
代碼演示:
// 先創建一個關鍵幀動畫對象
CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"position"];
NSValue *p1 = [NSValue valueWithCGPoint:CGPointMake(50, 50)];
NSValue *p2 = [NSValue valueWithCGPoint:CGPointMake(200, 50)];
NSValue *p3 = [NSValue valueWithCGPoint:CGPointMake(50, 200)];
NSValue *p4 = [NSValue valueWithCGPoint:CGPointMake(200, 200)];
anim.values = @[p1, p2, p3, p4];
anim.duration = 3;
[self.demoView.layer addAnimation:anim forKey:nil];
// 沿着橢圓進行轉動
// 設定動畫的速率,默認是勻速的
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(50, 50, 280, 170)];
anim.path = path.CGPath;
// 圖標抖動的效果
anim.values = @[@(-M_PI_4 * 0.3), @(M_PI_4 * 0.3), @(-M_PI_4 * 0.3)];
> 組動畫(CAAnimationGroup): 把所有其他的動畫添加到組裏, 這樣就可以按照添加的動畫一次執行
是 CAAnimation 的子類, 可以保存一組動畫對象, 將 CAAnimationGroup 對象加入層後, 組中所有動畫對象可以同時併發運行
默認情況下, 一組動畫對象是同時運行的, 也可以通過設置動畫對象的 beginTime 屬性來更改動畫的開始時間
> 轉場動畫(CATransition): 從一個場景轉換到另一個場景, 系統已經實現好了, 不需要我們再去寫.
CATransition 是 CAAnimation 的子類, 用於做轉場動畫, 能夠爲層提供移出屏幕和移入屏幕的動畫效果. iOS 比 Mac OS X 的轉場動畫效果少一點
UINavgationController 就是通過 CATransition 實現了將控制器的視圖推入屏幕的動畫效果
代碼演示:
// 1. 創建一個轉場動畫
CATransition *transition = [[CATransition alloc] init];
// 2. 設置轉場動畫的類型(轉場方式)
transition.type = @"cube";
// 3. 把轉場動畫添加到對應的控件上
[self.imgView.layer addAnimation:transition forKey:nil];
UIview 有個 block 方法也有個轉場動畫 [UIView animationDuratin....]
[UIView transitionWithView.....執行轉場動畫]
// 直接通過UIView的方式實現轉場動畫
[UIView transitionWithView:self.imgView duration:0.8 options:UIViewAnimationOptionTransitionFlipFromTop animations:nil completion:nil];
4. 所有的動畫都繼承自 CAAnimation
CAAnimation 遵守了一個 CAMediaTiming 的協議.
CAAnimation 裏面有個 duration 屬性.
CAAnimation 裏面有個 timingFunction 屬性