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

iOS 播放 GIF 的三種做法:精準控制每一幀的顯示時間

編輯:iOS 開發綜合

為什麼不能一概而論

GIF 由多張連續畫面組成,而每一幀的顯示時長未必相同。網路上流傳的許多範例都沒有處理各幀的停頓時間,結果就是所有畫面以固定速度播放——這顯然不總是符合原圖的節奏。

為了解決這個問題,可以自行撰寫一個解析工具類:讀出每一幀的顯示時間,並依該時間安排播放。整體思路三步:

  1. 用 ImageIO 的 CGImageSource 載入 GIF 檔案。
  2. 取得總幀數,以及每一幀對應的顯示時間。
  3. 用 CAKeyframeAnimation 依這些時間權重完成動畫。

工具類實作

// SvGifView.h
#import <UIKit/UIKit.h>

@interface SvGifView : UIView

- (id)initWithCenter:(CGPoint)center fileURL:(NSURL *)fileURL;  // 指定初始化
- (void)startGif;                                             // 開始播放
- (void)stopGif;                                              // 停止播放
+ (NSArray *)framesInGif:(NSURL *)fileURL;                    // 取出所有幀的 CGImageRef

@end
// SvGifView.m
#import "SvGifView.h"
#import <ImageIO/ImageIO.h>
#import <QuartzCore/CoreAnimation.h>

// 解析 GIF 資訊。之所以用 C 函數,是因為需要一次回傳多個值
void getFrameInfo(CFURLRef url, NSMutableArray *frames, NSMutableArray *delayTimes,
                  CGFloat *totalTime, CGFloat *gifWidth, CGFloat *gifHeight) {
    CGImageSourceRef gifSource = CGImageSourceCreateWithURL(url, NULL);

    size_t frameCount = CGImageSourceGetCount(gifSource);   // 總幀數
    for (size_t i = 0; i < frameCount; ++i) {
        // 取出每一幀
        CGImageRef frame = CGImageSourceCreateImageAtIndex(gifSource, i, NULL);
        [frames addObject:(id)frame];
        CGImageRelease(frame);

        // 取出該幀的屬性
        NSDictionary *dict = (NSDictionary *)CGImageSourceCopyPropertiesAtIndex(gifSource, i, NULL);

        // 取得 GIF 尺寸
        if (gifWidth != NULL && gifHeight != NULL) {
            *gifWidth  = [[dict valueForKey:(NSString *)kCGImagePropertyPixelWidth] floatValue];
            *gifHeight = [[dict valueForKey:(NSString *)kCGImagePropertyPixelHeight] floatValue];
        }

        // kCGImagePropertyGIFDelayTime 與 kCGImagePropertyGIFUnclampedDelayTime 數值相同
        NSDictionary *gifDict = [dict valueForKey:(NSString *)kCGImagePropertyGIFDictionary];
        [delayTimes addObject:[gifDict valueForKey:(NSString *)kCGImagePropertyGIFDelayTime]];

        if (totalTime) {
            *totalTime = *totalTime
                + [[gifDict valueForKey:(NSString *)kCGImagePropertyGIFDelayTime] floatValue];
        }
    }
}

@interface SvGifView() {
    NSMutableArray *_frames;
    NSMutableArray *_frameDelayTimes;
    CGFloat _totalTime;   // 秒
    CGFloat _width;
    CGFloat _height;
}
@end

@implementation SvGifView

- (id)initWithCenter:(CGPoint)center fileURL:(NSURL *)fileURL {
    self = [super initWithFrame:CGRectZero];
    if (self) {
        _frames = [[NSMutableArray alloc] init];
        _frameDelayTimes = [[NSMutableArray alloc] init];
        _width = 0;
        _height = 0;

        if (fileURL) {
            getFrameInfo((CFURLRef)fileURL, _frames, _frameDelayTimes,
                         &_totalTime, &_width, &_height);
        }

        self.frame = CGRectMake(0, 0, _width, _height);
        self.center = center;
    }
    return self;
}

+ (NSArray *)framesInGif:(NSURL *)fileURL {
    NSMutableArray *frames = [NSMutableArray arrayWithCapacity:3];
    NSMutableArray *delays = [NSMutableArray arrayWithCapacity:3];
    getFrameInfo((CFURLRef)fileURL, frames, delays, NULL, NULL, NULL);
    return frames;
}

- (void)startGif {
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];

    // 把每幀的累積時間換算成 0~1 的 keyTimes
    NSMutableArray *times = [NSMutableArray arrayWithCapacity:3];
    CGFloat currentTime = 0;
    int count = _frameDelayTimes.count;
    for (int i = 0; i < count; ++i) {
        [times addObject:[NSNumber numberWithFloat:(currentTime / _totalTime)]];
        currentTime += [[_frameDelayTimes objectAtIndex:i] floatValue];
    }
    [animation setKeyTimes:times];

    NSMutableArray *images = [NSMutableArray arrayWithCapacity:3];
    for (int i = 0; i < count; ++i) {
        [images addObject:[_frames objectAtIndex:i]];
    }

    [animation setValues:images];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
    animation.duration = _totalTime;
    animation.delegate = self;
    animation.repeatCount = 5;

    [self.layer addAnimation:animation forKey:@"gifAnimation"];
}

- (void)stopGif {
    [self.layer removeAllAnimations];
}

// 動畫結束後清掉 contents,避免最後一幀殘留
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    self.layer.contents = nil;
}

@end

程式碼不長,重點就在最開頭那個 C 函數——它負責解析 GIF。之所以寫成 C 函數而非方法,是因為需要一次回傳多項資訊,而 Objective-C 方法只能回傳單一值;C 與 Objective-C 本來就能方便地混用,用指標參數輸出多個結果是最直接的選擇。

關鍵技巧是 keyTimes:把每幀的 delayTime 累加成比例值(0 到 1 之間),再搭配線性 timing function,就能讓每一幀停留的時間與原圖一致。

另外兩種更省事的替代方案

1. 用 UIWebView 播放

// 設定位置和大小
CGRect frame = CGRectMake(50, 50, 0, 0);
frame.size = [UIImage imageNamed:@"guzhang.gif"].size;

// 讀取 gif 圖片數據
NSData *gif = [NSData dataWithContentsOfFile:
    [[NSBundle mainBundle] pathForResource:@"guzhang" ofType:@"gif"]];

UIWebView *webView = [[UIWebView alloc] initWithFrame:frame];
webView.userInteractionEnabled = NO;   // 使用者不可交互
[webView loadData:gif MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];
[self.view addSubview:webView];
[webView release];

這個做法最偷懶,瀏覽器本身就會正確處理各幀時距,缺點是得背上一整個 webview 的資源成本。

2. 拆成多張圖片,交給 UIImageView

UIImageView *gifImageView = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
NSArray *gifArray = [NSArray arrayWithObjects:
    [UIImage imageNamed:@"1"], [UIImage imageNamed:@"2"], [UIImage imageNamed:@"3"],
    [UIImage imageNamed:@"4"], [UIImage imageNamed:@"5"], [UIImage imageNamed:@"6"],
    [UIImage imageNamed:@"7"], [UIImage imageNamed:@"8"], [UIImage imageNamed:@"9"],
    [UIImage imageNamed:@"10"], [UIImage imageNamed:@"11"], [UIImage imageNamed:@"12"],
    [UIImage imageNamed:@"13"], [UIImage imageNamed:@"14"], [UIImage imageNamed:@"15"],
    [UIImage imageNamed:@"16"], [UIImage imageNamed:@"17"], [UIImage imageNamed:@"18"],
    [UIImage imageNamed:@"19"], [UIImage imageNamed:@"20"], [UIImage imageNamed:@"21"],
    [UIImage imageNamed:@"22"], nil];

gifImageView.animationImages = gifArray;      // 動畫圖片陣列
gifImageView.animationDuration = 5;           // 播放一輪的總時長
gifImageView.animationRepeatCount = 1;        // 重複次數
[gifImageView startAnimating];
[self.view addSubview:gifImageView];
[gifImageView release];

這個方法寫起來最簡單,但有個致命限制:它無法表達各幀不同的間隔,只能給定一個整體週期。因此只有在所有幀時距一致的 GIF 上,才能得到正確效果;遇到節奏不規則的圖,還是得回到 CAKeyframeAnimation 那條路。

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