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

iOS 動畫入門:從 beginAnimations 到 Block 動畫與彈簧效果

編輯:iOS 開發綜合

在 iOS 上實現動畫,本質上是在一段給定的時間內完成狀態的連續變化——背景色、frame 大小、位移、旋轉、透明度、縮放等等。本文從最老的寫法講到 Block 動畫,再談動畫串接與彈簧減速。

一、傳統動畫寫法(iOS 4.0 之前)

早期蘋果提供的是類似資料庫「事務」的編程模式:begin 標記開始、設定屬性、commit 提交。

例如實作一個 view 的淡入效果(alpha = 1 為全透明,0 為不透明):

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];                                    // 動畫時長 1 秒
[UIView setAnimationDelay:0.0];                                       // 不延遲
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationStopped)];      // 完成後的回呼

self.view.alpha = 0.0;                                                // 最終 alpha
self.view.frame = CGRectMake(10, 10, 50, 50);                         // 最終 frame

[UIView commitAnimations];                                            // 提交動畫

用 beginAnimations 標記動畫開始,設定各種屬性,最後以 commitAnimations 提交,之後系統接管並執行。

二、Block 動畫寫法(iOS 4.0 之後)

iOS 4 之後蘋果提供了一組重載函式,改以 block 傳入動畫內容:

+ (void)animateWithDuration:(NSTimeInterval)duration
                  animations:(void (^)(void))animations;

+ (void)animateWithDuration:(NSTimeInterval)duration
                  animations:(void (^)(void))animations
                 completion:(void (^)(BOOL finished))completion;

+ (void)animateWithDuration:(NSTimeInterval)duration
                      delay:(NSTimeInterval)delay
                    options:(UIViewAnimationOptions)options
                 animations:(void (^)(void))animations
                 completion:(void (^)(BOOL finished))completion;

+ (void)animateWithDuration:(NSTimeInterval)duration
                      delay:(NSTimeInterval)delay
    usingSpringWithDamping:(CGFloat)dampingRatio
     initialSpringVelocity:(CGFloat)velocity
                    options:(UIViewAnimationOptions)options
                 animations:(void (^)(void))animations
                 completion:(void (^)(BOOL finished))completion;

使用範例:

+ (void)fadeIn:(UIView *)view andAnimationDuration:(float)duration {
    [view setAlpha:0.0];
    NSLog(@"begin animation");

    [UIView animateWithDuration:duration
                     animations:^{
        [view setAlpha:1.0];
        NSLog(@"in animation block");
    }
                     completion:^(BOOL finished) {
        NSLog(@"completion animation");
    }];

    NSLog(@"exit fadeIn");
}

透過 duration、delay、options 等參數分別設定時間、延遲與執行選項。動畫主體寫在 animations block,完成後的邏輯寫在 completion block。之所以需要 completion,是為了給我們一個「動畫確實跑完之後」的執行入口(舊寫法靠 setAnimationDidStopSelector 達成同樣目的)。

三、一個關鍵觀念:動畫是非同步的

把動畫組裝好交給系統之後,程式不會被阻塞,會立刻往下執行。也就是說,把程式碼放在 NSLog(@"in animation block") 之後、NSLog(@"exit fadeIn") 之前,和放在 completion 裡,有本質上的區別——前者會在動畫還沒開始時就執行完畢。

completion 的 BOOL 參數有什麼用?它用來告知動畫是否真的執行完成。這很重要,因為動畫是可以被取消的(例如 [view.layer removeAllAnimations]),但無論是否取消,系統都會呼叫 completion 告知「動畫已結束」。可以這樣想像:手雷被丟出後會播放飛行模擬動畫,落地碰撞時飛行模擬結束,接著播放爆炸模擬;但如果手雷在半空被人接住,飛行模擬被取消,那後續是否爆炸就要另行判斷了。

另外,即使 duration 設為 0,completion 依然會被呼叫——雖然 duration 是 0,但本質上仍是非同步的,系統會在下一個 message loop 開始時立刻呼叫,此時 BOOL 參數仍是 YES。

若希望在動畫結束前不要讓其他邏輯插入,可以在提交動畫後做 message loop 輪詢:

+ (void)fadeIn:(UIView *)view andAnimationDuration:(float)duration andWait:(BOOL)wait {
    __block BOOL done = wait;   // wait = YES 表示要等動畫結束
    [view setAlpha:0.0];

    [UIView animateWithDuration:duration
                     animations:^{
        [view setAlpha:1.0];
    }
                     completion:^(BOOL finished) {
        done = NO;
    }];

    // 等待動畫結束
    while (done == YES) {
        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01]];
    }
}

不過這種做法會讓呼叫端同步阻塞,在目前的 iOS 開發中已很少使用。若真的需要序列化,用 completion 串接或 GCD 的 dispatch_group 都是更好的選擇。

四、常見動畫效果速查

縮放 —— 改動 view.transform

view.transform = CGAffineTransformMakeScale(0, 0);
[UIView animateWithDuration:duration animations:^{
    view.transform = CGAffineTransformIdentity;
} completion:^(BOOL finished) {
}];

淡入淡出 —— 改動 view.alpha

[view setAlpha:0.0];
[UIView animateWithDuration:duration animations:^{
    [view setAlpha:1.0];
} completion:^(BOOL finished) {
}];

位置移動 —— 改動 view.center

[UIView animateWithDuration:duration animations:^{
    view.center = CGPointMake(view.center.x - length, view.center.y);
} completion:^(BOOL finished) {
}];

旋轉 —— 改動 view.transform

[UIView animateWithDuration:duration animations:^{
    view.transform = CGAffineTransformMakeRotation(degreesToRadians(angle));
} completion:^(BOOL finished) {
}];

五、動畫串接(動畫鏈)

在一個動畫完成後接續下一個動畫,甚至串成多段形成動畫鏈:

這個帶回彈效果的气泡弹出動畫,由三段改變縮放值的動畫串行組成,每段都在前一段的 completion 中啟動下一段:

self.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.001, 0.001);
__unsafe_unretained typeof(self) reself = self;

[UIView animateWithDuration:0.3 / 1.5 animations:^{
    reself.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1.1, 1.1);
} completion:^(BOOL finished) {
    [UIView animateWithDuration:0.3 / 2 animations:^{
        reself.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.9, 0.9);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.3 / 2 animations:^{
            reself.transform = CGAffineTransformIdentity;
        }];
    }];
}];

拆解如下:

初始狀態:把 view 縮放到正常大小的 0.001 倍。

動畫 1(0.2 秒):放大到 1.1 倍。

動畫 2(0.15 秒):縮小到 0.9 倍。

動畫 3(0.15 秒):回復正常大小。

三段時間刻意不相等,正是為了模擬「先衝出去、再被拉回、最後定住」的手感。

六、彈簧減速動畫

+ (void)animateWithDuration:(NSTimeInterval)duration
                      delay:(NSTimeInterval)delay
     usingSpringWithDamping:(CGFloat)dampingRatio
      initialSpringVelocity:(CGFloat)velocity
                    options:(UIViewAnimationOptions)options
                 animations:(void (^)(void))animations
                 completion:(void (^)(BOOL finished))completion;

這個方法靠兩個參數實現近似彈簧的效果(帶加速度):

usingSpringWithDamping:(CGFloat)dampingRatio
 initialSpringVelocity:(CGFloat)velocity

上圖有兩個動畫:一個平穩減速停止,一個減速後帶回彈(近似碰撞)。

usingSpringWithDamping 標示彈簧的強度,範圍 0 ~ 1。等於 1 時,動畫會平滑且沒有上下擺動地減速到最終狀態;數值越小,擺動幅度越明顯。

initialSpringVelocity 標示 view 開始受到彈簧作用力時的初速度,範圍同樣是 0 ~ 1。假設整個動畫要移動 100 點,取值 1 表示初速為 100 點/秒。數值越小,起始速度越慢。

其實不用這個方法,靠串行多段方向相反的位移動畫(分別控制時間來模擬加減速)也能做出回彈效果,就是上面第五節的做法。兩者的取捨是:彈簧動畫程式碼短、曲線自然,但不易精確控制每一段的時序;手動串接程式碼長,卻能完全掌握節奏,適合需要與其他動畫精準對齊的場景。

七、幾個實務提醒

動畫屬性的選擇很重要。位移請改 center 或 transform 的 translation,不要動 frame 的 origin;縮放與旋轉請用 transform,不要改 bounds。改 frame 會觸發 layout 與 mask 重算,效能較差。

options 值得多用。UIViewAnimationOptionCurveEaseInOut 讓動畫起訖平順、UIViewAnimationOptionRepeat 可無限循環、.AllowUserInteraction 允許動畫期間使用者操作,這些都能顯著改善手感。

大量動畫請改用 Core Animation。UIView 動畫適合單一屬性的簡單變化;若同時要控制多個圖層、需要 keyframe 或時間函式,直接操作 CALayer 與 CABasicAnimation / CAKeyframeAnimation 會更合適。

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