iOS 開發中需要動畫的地方不少,最典型的是視圖控制器執行 segue 轉場的時候;同一個控制器內切換不同視圖時也常需要過場效果,有些元件加上動畫之後,整體質感會明顯提升。
做 iOS 開發久了會有一種錯覺,好像自己在當電影導演:安排不同布景、調度畫面切換。流暢的過場確實能為 App 增色不少。
Storyboard 裡建立視圖與控制器時就有一批動畫參數可調,但若只停在圖形介面層面,對背後的機制仍會一知半解,所以還是要從程式碼角度看一遍。
視圖控制器之間的切換(例如 presentViewController 或 popViewController),底層使用的是 CATransition。它同樣是基於 layer 的實作,用於切換不同視圖,但效果相對有限——比如無法滿足「兩個控制器的視圖同時在同一個 window 上演出」這種需求。若想用手勢驅動兩個控制器的視圖共同呈現動畫,CATransition 就力有未逮了。
至於同一個控制器內不同視圖之間的切換,改用 UIView 的 beginAnimations:context: 或 animateWithDuration:animations:completion: 等方法會更合適。
動畫的本質其實很樸素:在指定的時間內,逐步或反覆修改視圖的某些屬性,直到完成。常見可動的屬性包括:
frame、bounds、center:位置與尺寸;alpha:透明度;backgroundColor:背景色;contentStretch:拉伸變化;transform:仿射變換,涵蓋 Rotate(旋轉)、Invert(反轉)、Translate(位移)、Scale(縮放)。
一般動畫以每秒 30 幀呈現,人眼可辨識的門檻約為 24 幀,遊戲則常要求 60 幀。系統在設定好的時間內,依時間函數(緩入、緩出等)反覆修改這些屬性,改一次就換一個畫面,週而復始;在我們眼中,這便成了連續的動作。
談到 UIView 的屬性,就不得不提它的組成。UIView 其實是由 layer 組裝而成的,bounds、center 這些屬性都來自 CALayer。只要往視圖的 layer 上掛入 CAAnimation 物件,視圖動畫就成立了。
CAAnimation 是抽象類,具體子類主要有 CABasicAnimation 與 CAKeyframeAnimation。把動畫物件加進 UIView.layer,效果便會呈現。要注意的是,動畫播完之後,layer 的屬性會回到初始值;若想保留結果,必須在掛上動畫時另外約定。
先建立一個 CALayer,把它的 contents 設為 UIImage 的 CGImage,再對這個圖層做處理:
CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"]; scaleAnimation.toValue = scaleFactor; scaleAnimation.duration = 3.0f; scaleAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
完整流程如下:
- (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;
// 把圖層掛到 view 的 layer 上
[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];
[logoLayer addAnimation:scaleAnimation forKey:@"transformAnimation"];
}
若在動畫結束後需要保存結果,則要在 delegate 的 animationDidStop:finished: 中把 model layer 的屬性一併設為 toValue,讓視覺上不跳回原點。
上面的寫法只處理單一視圖。若要多個動畫同時上演,就得靠 CAAnimationGroup:把多個 CABasicAnimation 放進陣列,交給動畫組,再把動畫組掛到圖層上。
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"];
若想在圖層上做更細緻的控制,就得往 CALayer 的子類發展,常見的有:
CAScrollLayer,簡化顯示圖層的某一部分;CATextLayer,便於從字串產生文字內容;CATiledLayer,適合顯示超大或複雜圖片;CAOpenGLLayer,提供 OpenGL ES 的渲染環境。
CALayer 能對 UIView 做出許多額外設定,例如陰影、邊框、圓角與透明效果,這些都很實用。重要屬性包含:
shadowPath,指定陰影位置;shadowOffset,陰影在 X 與 Y 軸上的延伸方向與大小;shadowOpacity,陰影透明度;shadowRadius,陰影由外而內的漸變距離;masksToBounds,防止子圖層溢出父圖層,需要時設為 YES;borderWidth 與 borderColor,邊框寬度與顏色;bounds,控制尺寸但不影響位置;opacity,整體透明度;cornerRadius,圓角半徑。
這些屬性與 UIView 的屬性頗為相似,卻能做到 UIView 做不到的事。實際上,UIKit 裡那些 UITextField、UILabel、UIButton,本質上都是 UIView 的擴充,只是封裝好方便使用而已。
iOS 的動畫可以視為從 layer 這一層開始:往 layer 掛上 CABasicAnimation,觸發時機通常在 viewDidAppear 之後。因為 CABasicAnimation 稍嫌繁瑣,Apple 又封裝出 CATransition,但功能有限,只涵蓋幾種基本過場;再從便利性的角度出發,UIView 上才有了 beginAnimations: 與 animateWithDuration: 這類更親切的介面。
不過,一旦要實現複雜且真正吸引人的動畫效果,功課還是要下在 CALayer 這一整層上。