您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 動畫入門:指示器、序列幀、UIView 動畫與 CADisplayLink

編輯:iOS 相關資訊

iOS 的動畫手段不少,難度卻都不高。這篇把四種常見做法整理在一起:等待提示用的 UIActivityIndicatorView、逐格播放的 UIImageView 序列幀、最通用的 UIView 動畫,以及跟著螢幕刷新走的 CADisplayLink。

一、UIActivityIndicatorView:轉圈圈

核心只要記住 isAnimating 這個查詢屬性,就能做出「點一下開始、再點一下停止」的切換。

實務上很多人會直接用第三方庫 SVProgressHUD,一行就能顯示帶遮罩的等待提示:

[SVProgressHUD showWithStatus:@"網絡加載中" maskType:SVProgressHUDMaskTypeGradient];
[SVProgressHUD dismiss];

搭配 NSTimer 做定時收起:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if ([_indicatorView isAnimating]) {
        [SVProgressHUD dismiss];
        [_indicatorView stopAnimating];
    } else {
        // 注意:maskType 會讓當前視圖無法接收觸摸事件
        [SVProgressHUD showWithStatus:@"等會~~~" maskType:SVProgressHUDMaskTypeGradient];
        [_indicatorView startAnimating];

        [NSTimer scheduledTimerWithTimeInterval:2.0
                                         target:self
                                       selector:@selector(updateTimer:)
                                       userInfo:nil
                                        repeats:NO];
    }
}

- (void)updateTimer:(NSTimer *)timer
{
    [SVProgressHUD dismiss];
    [_indicatorView stopAnimating];
    [timer invalidate];   // 關閉計時器
}

NSTimer 的五個參數依序是:時間間隔、target、觸發時呼叫的方法、userInfo、是否重複。回呼方法的參數固定是 NSTimer *,善用它就不需要額外的成員變數。

二、UIImageView 序列幀動畫

三個關鍵屬性:animationImages(要播放的圖片陣列)、animationDuration(播放一輪的總時間)、animationRepeatCount(重複次數)。方法則是 startAnimating、stopAnimating、isAnimating。

- (void)createZhaoyunImage
{
    NSMutableArray *images = [NSMutableArray array];
    for (int i = 1; i < 11; i++) {
        NSString *fileName = [NSString stringWithFormat:@"/images/zy/%d.png", i];
        [images addObject:[UIImage imageNamed:fileName]];
    }

    [_zhaoyunImage setImage:images[0]];
    [_zhaoyunImage setAnimationImages:images];
    [_zhaoyunImage setAnimationDuration:1.0f];   // 10 張圖播完一輪 1 秒
    [_zhaoyunImage startAnimating];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if ([_zhaoyunImage isAnimating]) {
        // 停止後顯示的是 animationImages 指定的圖,而非當前播放到的那一格
        [_zhaoyunImage stopAnimating];
    } else {
        [_zhaoyunImage startAnimating];
    }
}

動態調整播放速度

做拖曳小鳥的效果時,希望手指按住時翅膀拍快一點、放開後恢復悠閒。修改播放中動畫有固定三步:先 stop、再 set duration、最後 start。

- (void)dragBird:(UIPanGestureRecognizer *)sender
{
    CGPoint location = [sender locationInView:self.view];

    if (sender.state == UIGestureRecognizerStateChanged) {
        // 手勢進行中:手指還沒離開螢幕
        [_birdImage stopAnimating];
        [_birdImage setAnimationDuration:0.2f];   // 拍快一點
        [_birdImage startAnimating];
        [_birdImage setCenter:location];          // 跟著手指跑
    } else if (sender.state == UIGestureRecognizerStateEnded) {
        // 手放開:恢復原本節奏
        [_birdImage stopAnimating];
        [_birdImage setAnimationDuration:1.2f];
        [_birdImage startAnimating];
    }
}

- (void)createBirdImage
{
    NSArray *images = @[[UIImage imageNamed:@"/images/bird1.png"],
                        [UIImage imageNamed:@"/images/bird2.png"]];
    [_birdImage setAnimationImages:images];
    [_birdImage setAnimationDuration:1.2f];
    [_birdImage startAnimating];

    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(dragBird:)];
    [_birdImage addGestureRecognizer:pan];

    // UIImageView 預設不接收觸摸,記得打開
    [_birdImage setUserInteractionEnabled:YES];
}

三、CADisplayLink:跟著螢幕刷新跑的時鐘

CADisplayLink 是一種由螢幕刷新觸發的計時器,每秒大約回呼 60 次,非常適合做遊戲迴圈。使用前需引入 QuartzCore 框架。

使用步驟:建立 display link 並指定回呼方法,然後把它加入主 Run Loop。

@interface ViewController ()
{
    CADisplayLink *_gameTimer;
    CFTimeInterval _startTime;
    int steps;
}
@end

@implementation ViewController

// 做法一:用時間差判斷
- (void)updateTimer:(CADisplayLink *)sender
{
    if (_startTime == 0) {
        _startTime = sender.timestamp;   // 第一次觸發,記錄起點
    }

    CFTimeInterval deltaTime = sender.timestamp - _startTime;
    if (deltaTime > 1.0) {
        NSLog(@"時鐘觸發了 %f", sender.timestamp);
        _startTime = sender.timestamp;   // 更新起點
    }
}

// 做法二:用次數判斷
- (void)step
{
    if (steps % 10 == 0) {
        NSLog(@"時鐘觸發了!第 %d 次", steps);
    }
    steps++;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    _startTime = 0.0f;
    steps = 0;

    _gameTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(step)];
    // 一定要加入 Run Loop,否則不會被觸發
    [_gameTimer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}
@end

綜合範例:飄雪效果

把 CADisplayLink 與 UIView 動畫結合,就能做出不錯的視覺效果:

- (void)step
{
    if (steps % 10 != 0) return;

    UIImageView *snow = [[UIImageView alloc] initWithImage:_snowImage];

    // 隨機大小、透明度與起終點
    CGFloat r = arc4random() % 5 + 10;
    [snow setFrame:CGRectMake(0, 0, r, r)];
    [snow setAlpha:arc4random() % 10 / 10.0f];

    CGPoint startPoint = CGPointMake(arc4random() % 320, -30.0);
    CGPoint endPoint   = CGPointMake(arc4random() % 320, 490);
    [snow setCenter:startPoint];
    [self.view addSubview:snow];

    [UIView animateWithDuration:6.0f
                          delay:0.0f
                        options:UIViewAnimationOptionCurveEaseIn
                     animations:^{
        [snow setCenter:endPoint];
        [snow setAlpha:0.2f];
        [snow setTransform:CGAffineTransformMakeRotation(M_PI)];
    } completion:^(BOOL finished) {
        // 動畫結束後務必移除,否則視圖層會無限累積
        [snow removeFromSuperview];
    }];
}

四、選擇建議

  • 只是「載入中」提示:UIActivityIndicatorView 或 SVProgressHUD。
  • 幀數不多的角色動畫:UIImageView 序列幀,實作最簡單。
  • 位移、縮放、旋轉、透明度變化:UIView 動畫首選。
  • 需要與邏輯、碰撞偵測同步的遊戲迴圈:CADisplayLink。

最後提醒一個常被忽略的細節:無論哪種動畫,只要涉及建立物件或計時器,都要想清楚「誰負責清掉它」。忘記 invalidate 計時器、忘記 removeFromSuperview,都是效能與記憶體問題的常見來源。

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