iOS 的動畫體系可以分成兩大層次:UIView 動畫(方便、基於屬性)與 CALayer 動畫(強大、基於 Core Animation)。本文依序整理兩者的所有主要形式與程式碼骨架。
- (IBAction)pressPropertyAnimation:(id)sender
{
// 1. 準備動畫
// 參數1: 動畫名稱,用於區分多個動畫
// 參數2: context,OC 傳 NULL
[UIView beginAnimations:@"改變大小" context:NULL];
// 動畫期間可設定各項屬性
[UIView setAnimationDuration:2]; // 持續時間
[UIView setAnimationDelegate:self];
[UIView setAnimationWillStartSelector:@selector(startAnimation)];
// [UIView setAnimationDelay:1]; // 延遲執行
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; // 時間曲線
[UIView setAnimationRepeatCount:20]; // 重複次數
[UIView setAnimationRepeatAutoreverses:YES]; // 往返執行(需先設重複次數)
// 2. 修改 view 屬性,可一次改多個
// 注意:只有 frame、center、bounds、backgroundColor、alpha、transform 可動畫
self.changeView.frame = CGRectMake(110, 100, 100, 100);
self.changeView.backgroundColor =
[UIColor colorWithRed:arc4random() % 256 / 255.0
green:arc4random() % 256 / 255.0
blue:arc4random() % 256 / 255.0
alpha:0.5];
// 3. 提交並執行
[UIView commitAnimations];
}
- (IBAction)pressTransitionAnimation:(id)sender
{
[UIView beginAnimations:@"過度動畫" context:NULL];
[UIView setAnimationDuration:5];
[UIView setAnimationRepeatCount:50];
// 參數1: 過場樣式
// 參數2: 對哪個 view 套用
// 參數3: 是否使用快取(先截圖再變換,效能較好)
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft
forView:self.changeView
cache:YES];
self.changeView.backgroundColor =
[UIColor colorWithRed:arc4random() % 256 / 255.0
green:arc4random() % 256 / 255.0
blue:arc4random() % 256 / 255.0
alpha:0.5];
[UIView commitAnimations];
}
Block 動畫本質上是對上述動畫 API 的封裝,一行就能完成。
- (IBAction)pressBlockAnimation:(id)sender
{
// 最簡單形式:只有 duration 與 animations
[UIView animateWithDuration:2
animations:^{
self.changeView.backgroundColor = [UIColor orangeColor];
}];
// 帶完成回呼
[UIView animateWithDuration:2
animations:^{
self.changeView.backgroundColor = [UIColor orangeColor];
}
completion:^(BOOL finished) {
if (finished) NSLog(@"finished");
}];
// 完整形式:duration / delay / options / animations / completion
[UIView animateWithDuration:2
delay:1
options:UIViewAnimationOptionCurveEaseInOut
animations:^{
self.changeView.backgroundColor = [UIColor orangeColor];
}
completion:^(BOOL finished) {
if (finished) NSLog(@"finished");
}];
// 過場動畫的 block 版本
[UIView transitionWithView:self.changeView
duration:2
options:UIViewAnimationOptionTransitionFlipFromLeft
animations:^{
self.changeView.backgroundColor = [UIColor orangeColor];
}
completion:^(BOOL finished) {
if (finished) NSLog(@"finished");
}];
}
// 動畫即將開始
- (void)animationWillStart:(NSString *)animationID context:(void *)context
{
NSLog(@"start: %@, %@", animationID, context);
}
// 動畫結束
- (void)animationDidStop:(NSString *)animationID
finished:(NSNumber *)finished
context:(void *)context
{
NSLog(@"stop: %@, %@", animationID, context);
}
理解這個關係是學 CALayer 動畫的基礎:
因此修改 layer 的外觀屬性,不需要呼叫 setNeedsDisplay:
self.changeView.layer.cornerRadius = 100; // 圓角(需 view 為正方形才是正圓) self.changeView.layer.borderWidth = 1; self.changeView.layer.borderColor = [UIColor orangeColor].CGColor; // layer 用 CGColor self.changeView.layer.shadowOffset = CGSizeMake(50, 100); // width 水平、height 垂直 self.changeView.layer.shadowColor = [UIColor grayColor].CGColor; self.changeView.layer.shadowOpacity = 1; // 0 ~ 1,預設 0(全透明)
注意 UIColor 與 CGColor 的轉換——UIView 用 UIColor,CALayer 用 CGColorRef。
類別繼承關係:
CAAnimation 抽象類別,不可直接使用
└── CAPropertyAnimation 抽象子類別,需再繼承
├── CABasicAnimation 基本動畫
└── CAKeyframeAnimation 關鍵幀動畫
CATransition 過場動畫
CAAnimationGroup 組合動畫
- (IBAction)pressBasicAnimation:(id)sender
{
// KeyPath 是 layer 的屬性名(KVC 路徑),只有標記為 animatable 的才可動
CABasicAnimation *basic = [CABasicAnimation animationWithKeyPath:@"bounds"];
basic.duration = 2;
basic.fromValue = [NSValue valueWithCGRect:
CGRectMake(0, 0,
self.changeView.bounds.size.width,
self.changeView.bounds.size.height)];
basic.toValue = [NSValue valueWithCGRect:CGRectMake(0, 0, 300, 300)];
// key 用來區分動畫
[self.changeView.layer addAnimation:basic forKey:@"changeBounds"];
}
重要觀念:CABasicAnimation 不會真正改變 model layer 的屬性值。動畫結束後,若不設 fillMode 與 removedOnCompletion,畫面會瞬間跳回原狀。要「停在最後」,必須同時修改 model layer 的值。
- (IBAction)pressKeyFrameAnimation:(id)sender
{
CAKeyframeAnimation *keyFrame =
[CAKeyframeAnimation animationWithKeyPath:@"backgroundColor"];
keyFrame.duration = 10;
keyFrame.values = @[ (id)[UIColor redColor].CGColor,
(id)[UIColor orangeColor].CGColor,
(id)[UIColor yellowColor].CGColor,
(id)[UIColor greenColor].CGColor,
(id)[UIColor blueColor].CGColor ];
// keyTimes 對應每個 value 出現的時刻,範圍 0~1,必須遞增
// 註:keyTimes 的第一個值慣例上為 0,不宜修改
keyFrame.keyTimes = @[ @(0.3), @(0.5), @(0.6), @(0.7), @(0.9) ];
[self.changeView.layer addAnimation:keyFrame forKey:nil];
}
也可以改用 path 屬性讓物件沿著一條 UIBezierPath 移動,或提供 timingFunctions 為每一段設定獨立的速度曲線。
- (IBAction)pressTransition:(id)sender
{
CATransition *transition = [CATransition animation];
transition.duration = 2;
transition.type = kCATransitionReveal; // 樣式
transition.subtype = kCATransitionFromTop; // 方向
[self.changeView.layer addAnimation:transition forKey:nil];
}
- (IBAction)pressAnimationGroup:(id)sender
{
CABasicAnimation *basic = [CABasicAnimation animationWithKeyPath:@"bounds"];
basic.duration = 2;
basic.fromValue = [NSValue valueWithCGRect:self.changeView.bounds];
basic.toValue = [NSValue valueWithCGRect:CGRectMake(0, 0, 300, 300)];
CAKeyframeAnimation *keyFrame =
[CAKeyframeAnimation animationWithKeyPath:@"backgroundColor"];
keyFrame.duration = 5;
keyFrame.values = @[ (id)[UIColor redColor].CGColor,
(id)[UIColor orangeColor].CGColor,
(id)[UIColor yellowColor].CGColor,
(id)[UIColor greenColor].CGColor,
(id)[UIColor blueColor].CGColor ];
CAAnimationGroup *group = [CAAnimationGroup animation];
// 關於 group 的 duration:
// 若 group duration > 最長的子動畫,實際以子動畫中最長者為準
// 若 group duration < 最長的子動畫,實際以 group 的 duration 為準
// 最佳实践是讓 group duration 等於子動畫中最長的 duration
group.duration = 5;
group.animations = @[ basic, keyFrame ];
[self.changeView.layer addAnimation:group forKey:nil];
}
UIView animateWithDuration:,程式碼最短,且能與 Auto Layout 協同。UIView transitionWithView: 或 CATransition。layoutIfNeeded 並包在動畫 block 內。UIAccessibilityIsReduceMotionEnabled() 並提供降低動效的替代方案。兩層動畫體系並不互斥:實務上常見的做法是用 UIView block 動畫處理版面與透明度,同時用 CABasicAnimation 處理陰影、漸層等 layer 專屬效果,兩者可以在同一段程式碼中並行。