您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 動畫總覽:UIView 動畫與 CALayer 動畫的完整用法

編輯:iOS 開發綜合

iOS 的動畫體系可以分成兩大層次:UIView 動畫(方便、基於屬性)與 CALayer 動畫(強大、基於 Core Animation)。本文依序整理兩者的所有主要形式與程式碼骨架。

一、UIView 動畫

1. 屬性動畫(begin/commit 舊式寫法)

- (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];
}

2. 過場動畫(Transition)

- (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];
}

3. Block 動畫(現代寫法)

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");
    }];
}

4. 動畫委派方法

// 動畫即將開始
- (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);
}

二、UIView 與 CALayer 的關係

理解這個關係是學 CALayer 動畫的基礎:

  • UIView 負責事件與版面:處理 touches、gesture、frame 計算與顯示責任
  • CALayer 負責內容渲染:它才是真正畫東西的那一層,且是 UIView 的 readonly 屬性

因此修改 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。

三、CALayer 動畫(CAAnimation)

類別繼承關係:

CAAnimation            抽象類別,不可直接使用
└── CAPropertyAnimation    抽象子類別,需再繼承
    ├── CABasicAnimation       基本動畫
    └── CAKeyframeAnimation    關鍵幀動畫
CATransition                  過場動畫
CAAnimationGroup              組合動畫

1. CABasicAnimation:在两值之間插值

- (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 的值。

2. CAKeyframeAnimation:沿多個關鍵點變化

- (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 為每一段設定獨立的速度曲線。

3. CATransition:整層過場

- (IBAction)pressTransition:(id)sender
{
    CATransition *transition = [CATransition animation];
    transition.duration = 2;
    transition.type    = kCATransitionReveal;    // 樣式
    transition.subtype = kCATransitionFromTop;   // 方向

    [self.changeView.layer addAnimation:transition forKey:nil];
}

4. CAAnimationGroup:多動畫同步

- (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];
}

該選哪一種

  • 只要改 frame / alpha / 背景色:用 UIView animateWithDuration:,程式碼最短,且能與 Auto Layout 協同。
  • 需要轉場、翻頁、換 rootView:用 UIView transitionWithView: 或 CATransition。
  • 需要圓角、陰影、渐变、3D transform:這些屬性只有 layer 才有,必須走 CALayer 動畫。
  • 路徑運動、多段不同速度:CAKeyframeAnimation。
  • 多個動畫要精準同步:CAAnimationGroup,或使用 CATransaction 設定共同 duration 與 completion。

常見錯誤

  • 不要在動畫 block 中改 Auto Layout 約束常數:正確做法是改常數後呼叫 layoutIfNeeded 並包在動畫 block 內。
  • 動畫屬性有限:UIView 動畫只支援 frame、bounds、center、transform、alpha、backgroundColor。改文字、改顏色的 CGColor 都必須走 layer。
  • CAAnimation 不做 model 變更:這是 Core Animation 與 UIView 動畫最大的觀念差異,理解了才不會出現「動畫跑完畫面跳回去」的困惑。
  • 記得處理 reduce motion:無障礙需求下,可檢查 UIAccessibilityIsReduceMotionEnabled() 並提供降低動效的替代方案。

兩層動畫體系並不互斥:實務上常見的做法是用 UIView block 動畫處理版面與透明度,同時用 CABasicAnimation 處理陰影、漸層等 layer 專屬效果,兩者可以在同一段程式碼中並行。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved