Core Animation 的動畫家族龐大,但日常開發真正高頻的只有三種層次:基本動畫、關鍵幀動畫,以及搭配緩動函數模擬物理效果。難度是階梯式往上加的。
寫法最簡單,能表達的效果也最受限——本質上就是「從 A 到 B」。流程大致是:
#1. 建立原始的 UI 或畫面
#2. 建立 CABasicAnimation 實例,設定 keyPath/duration/fromValue/toValue
#3. 設定動畫結束後真正停留的位置
#4. 把動畫加到 layer 上
做一個紅色圓形從上往下掉的例子:
// 設置原始畫面 UIView *showView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; showView.layer.masksToBounds = YES; showView.layer.cornerRadius = 50.f; showView.layer.backgroundColor = [UIColor redColor].CGColor; [self.view addSubview:showView]; // 創建基本動畫 CABasicAnimation *basicAnimation = [CABasicAnimation animation]; basicAnimation.keyPath = @"position"; basicAnimation.duration = 4.0f; basicAnimation.fromValue = [NSValue valueWithCGPoint:showView.center]; basicAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(50, 300)]; // 設置動畫結束位置 showView.center = CGPointMake(50, 300); // 添加動畫到 layer 層 [showView.layer addAnimation:basicAnimation forKey:nil];
這裡有個觀念要記牢:CA 動畫不真正改動 model layer 的值,所以務必手動把 showView.center 設成終點,否則動畫一結束物件會瞬間跳回原點。
跟基本動畫幾乎一樣,差別是 keyPath 之外多了一個 values 陣列,可以塞進任意多個路徑點。步驟:
#1. 建立原始畫面
#2. 建立 CAKeyframeAnimation,設定 keyPath/duration/values
#3. 設定最終停留位置
#4. 加到 layer
讓圓形左右搖晃著墜落:
UIView *showView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
showView.layer.masksToBounds = YES;
showView.layer.cornerRadius = 50.f;
showView.layer.backgroundColor = [UIColor redColor].CGColor;
[self.view addSubview:showView];
CAKeyframeAnimation *keyFrameAnimation = [CAKeyframeAnimation animation];
keyFrameAnimation.keyPath = @"position";
keyFrameAnimation.duration = 4.0f;
keyFrameAnimation.values = @[
[NSValue valueWithCGPoint:showView.center],
[NSValue valueWithCGPoint:CGPointMake(100, 100)],
[NSValue valueWithCGPoint:CGPointMake(50, 150)],
[NSValue valueWithCGPoint:CGPointMake(200, 200)]
];
showView.center = CGPointMake(200, 200);
[showView.layer addAnimation:keyFrameAnimation forKey:nil];
要做出彈簧、回彈這類擬真效果,硬寫關鍵幀點會崩潰。好在有人已經把物理曲線算好了——緩動函數(Easing Function)就是拿時間比例代入函式、算出對應位移的數學工具。
開源的 EasingAnimation 庫把這套計算封裝好了:
https://github.com/YouXianMing/EasingAnimation
底下有哪些曲線可以查庫內的緩動函數對照表。以下示範小球落地的回彈:
UIView *showView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
showView.layer.masksToBounds = YES;
showView.layer.cornerRadius = 50.f;
showView.layer.backgroundColor = [UIColor redColor].CGColor;
[self.view addSubview:showView];
CAKeyframeAnimation *keyFrameAnimation = [CAKeyframeAnimation animation];
keyFrameAnimation.keyPath = @"position";
keyFrameAnimation.duration = 4.0f;
// 關鍵處:用緩動函數計算點路徑
keyFrameAnimation.values = [YXEasing calculateFrameFromPoint:showView.center
toPoint:CGPointMake(50, 300)
func:BounceEaseOut
frameCount:4.0f * 30];
showView.center = CGPointMake(50, 300);
[showView.layer addAnimation:keyFrameAnimation forKey:nil];
關鍵在 frameCount:fps 乘以秒數決定取樣密度,點算得越細,看起來就越順。這招等於把「物理模擬」的難題外包給數學函式,自己只負責把結果餵給關鍵幀動畫。