iOS 開發中需要動畫的地方很多,最典型的是視圖控制器的 segue 切換;同一個視圖控制器內切換不同視圖時也需要動畫,還有些元件加上動畫會更出色。
做 iOS 開發時常有一種當導演的錯覺:安排不同布景、決定畫面如何切換。流暢的畫面確實能為 App 增色不少。
storyboard 裡可以做一些動畫設定,但從程式碼角度仍得理解其實作過程。
跨視圖控制器切換(presentViewController、popViewController)使用的是 CATransition。它同樣基於 layer 實作,但效果有限,例如無法滿足兩個視圖控制器的視圖在同一個 window 上呈現的動畫——想用 panGestureController 做這件事是行不通的。
同一視圖控制器內的不同視圖切換,則可用 UIView 的 beginAnimations:nil 或 animateWithDuration:animations:completion: 等方法實作。
動畫的本質,是在設定時間內透過時間函數(緩入、緩出等)反覆或逐步修改視圖屬性,肉眼看來就成了連續動作。可動的屬性包括:
普通動畫約 30 幀每秒,肉眼可辨識約 24 幀,遊戲則常要求 60 幀。
UIView 其實是由 layer 組成的,bounds、center 等屬性都來自 CALayer。在視圖的 layer 上加入 CAAnimation 物件即可實現動畫。CAAnimation 是抽象類別,實體類別有 CABasicAnimation 與 CAKeyframeAnimation。
注意:動畫完成後,layer 的屬性會恢復初始值。若要保留動畫結果,必須在加入動畫時額外做約定設定。
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor blackColor];
self.title = [[self class] displayName];
UIImage *image = [UIImage imageNamed:@"batman.png"];
logoLayer = [CALayer layer];
logoLayer.bounds = CGRectMake(0, 0, image.size.width, image.size.height);
logoLayer.position = CGPointMake(160, 180);
logoLayer.contents = (id)image.CGImage;
// 把 layer 加為 UIView 的 sublayer
[self.view.layer addSublayer:logoLayer];
}
- (void)scaleByFactor:(CGFloat)factor {
CABasicAnimation *scaleAnimation =
[CABasicAnimation animationWithKeyPath:@"transform.scale"];
NSNumber *scaleFactor = [NSNumber numberWithFloat:factor];
scaleAnimation.toValue = scaleFactor;
scaleAnimation.duration = 3.0f;
scaleAnimation.timingFunction =
[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
// 設定 model layer 的屬性,讓動畫停在 toValue 狀態
[logoLayer addAnimation:scaleAnimation forKey:@"transformAnimation"];
}
動畫結束後若要保存結果,可在 delegate 的 - (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag 中處理。
CAAnimationGroup *animationGroup = [CAAnimationGroup animation]; animationGroup.duration = 2.0f; animationGroup.autoreverses = YES; animationGroup.repeatCount = HUGE_VALF; [animationGroup setAnimations:[NSArray arrayWithObjects:rotationAnimation, scaleAnimation, nil]]; [logoLayer addAnimation:animationGroup forKey:@"animationGroup"];
這些屬性與 UIView 很像,卻能實現 UIView 做不到的效果,例如陰影、邊框、圓角與透明處理。實際上 UIKit 中的 UITextField、UILabel、UIButton 等,本質上就是 UIView 的擴充與封裝。
iOS 動畫是從 layer 層開始的:往 layer 加入 CABasicAnimation,其實是觸發 layer 預先定義好的某個功能點,在 viewDidAppear 後執行。因為 CABasicAnimation 稍嫌複雜,iOS 又封裝出 CATransition,但它能做的事有限;再從便利性的角度,UIView 提供了 beginAnimations 與 animateWithDuration 等方法。若要更複雜、更吸引人的動畫,仍得回到 CALayer 上下功夫。