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

iOS 播放 GIF 的多種方案:原生做法與第三方庫全面比較

編輯:iOS 開發綜合

要在 iOS 上顯示 GIF 動態圖,蘋果並沒有提供現成的元件。實務上大致分兩條路:用系統既有元件「變相」播放,或引入專門處理 GIF 的第三方庫。本文把常見方案逐一實作並比較特性。

原生方案一:UIWebView

把 GIF 資料直接餵給 UIWebView,讓 WebKit 幫你解圖並播放。

特點:載入時間稍長,但解繪品質與流暢度較佳。

// 以 WebView 顯示 GIF
- (void)showGifImageWithWebView {
    // 讀取 bundle 中的 GIF 資料
    NSData *gifData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"earthGif" ofType:@"gif"]];

    UIWebView *imageWebView = [[UIWebView alloc] initWithFrame:CGRectMake(112, 302, 132, 102)];
    imageWebView.userInteractionEnabled = NO;   // 純展示,不需要互動

    [imageWebView loadData:gifData MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];
    [self.view addSubview:imageWebView];
}

原生方案二:UIImageView + CAKeyframeAnimation

先把 GIF 拆成一張張 UIImage,再用 CAKeyframeAnimation 依每幀的顯示時間逐格切換。

特點:載入速度快,效能不如 WebView,但最大的優點是容易擴充——你能自己控制播放、暫停、指定第幾幀。

1. 為 UIImageView 建立分類

UIImage+Tool.h:

#import <UIKit/UIKit.h>

@interface UIImageView (Tool)

/** 解析 GIF 檔案資料,block 會把解析結果回傳出來 */
- (void)getGifImageWithUrk:(NSURL *)url
                returnData:(void(^)(NSArray<UIImage *> *imageArray,
                                    NSArray<NSNumber *> *timeArray,
                                    CGFloat totalTime,
                                    NSArray<NSNumber *> *widths,
                                    NSArray<NSNumber *> *heights))dataBlock;

/** 為 UIImageView 加上設定 GIF 內容的便利方法 */
- (void)yh_setImage:(NSURL *)imageUrl;

@end

UIImage+Tool.m:

#import "UIImageView+Tool.h"

// 需要引入 ImageIO 才能使用 CGImageSource 系列 API
#import <ImageIO/ImageIO.h>

@implementation UIImageView (Tool)

// 解析 GIF 資料,block 中把解析結果帶出來
- (void)getGifImageWithUrk:(NSURL *)url
                returnData:(void(^)(NSArray<UIImage *> *imageArray,
                                    NSArray<NSNumber *> *timeArray,
                                    CGFloat totalTime,
                                    NSArray<NSNumber *> *widths,
                                    NSArray<NSNumber *> *heights))dataBlock {

    // 以檔案 URL 建立影像來源
    CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)url, NULL);

    // GIF 裡一共有幾張圖
    size_t count = CGImageSourceGetCount(source);

    float allTime = 0;                              // 播放一輪的總時間
    NSMutableArray *imageArray  = [[NSMutableArray alloc] init];  // 所有影格
    NSMutableArray *timeArray   = [[NSMutableArray alloc] init];  // 每幀顯示時間
    NSMutableArray *widthArray  = [[NSMutableArray alloc] init];  // 每幀寬度
    NSMutableArray *heightArray = [[NSMutableArray alloc] init];  // 每幀高度

    for (size_t i = 0; i < count; i++) {
        CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);
        [imageArray addObject:(__bridge UIImage *)(image)];
        CGImageRelease(image);

        // 取出這一幀的屬性
        NSDictionary *info = (__bridge NSDictionary *)CGImageSourceCopyPropertiesAtIndex(source, i, NULL);
        CGFloat width  = [[info objectForKey:(__bridge NSString *)kCGImagePropertyPixelWidth] floatValue];
        CGFloat height = [[info objectForKey:(__bridge NSString *)kCGImagePropertyPixelHeight] floatValue];
        [widthArray addObject:[NSNumber numberWithFloat:width]];
        [heightArray addObject:[NSNumber numberWithFloat:height]];

        // GIF 特有的資訊字典裡藏著這一幀的顯示秒數
        NSDictionary *timeDic = [info objectForKey:(__bridge NSString *)kCGImagePropertyGIFDictionary];
        CGFloat time = [[timeDic objectForKey:(__bridge NSString *)kCGImagePropertyGIFDelayTime] floatValue];
        allTime += time;
        [timeArray addObject:[NSNumber numberWithFloat:time]];
    }

    dataBlock(imageArray, timeArray, allTime, widthArray, heightArray);
}

- (void)yh_setImage:(NSURL *)imageUrl {
    __weak id __self = self;

    [self getGifImageWithUrk:imageUrl returnData:^(NSArray<UIImage *> *imageArray,
                                                  NSArray<NSNumber *> *timeArray,
                                                  CGFloat totalTime,
                                                  NSArray<NSNumber *> *widths,
                                                  NSArray<NSNumber *> *heights) {
        CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
        NSMutableArray *times = [[NSMutableArray alloc] init];
        float currentTime = 0;

        // keyTimes 需要「比例」而不是絕對時間,因此逐幀正規化
        for (int i = 0; i < imageArray.count; i++) {
            [times addObject:[NSNumber numberWithFloat:currentTime / totalTime]];
            currentTime += [timeArray[i] floatValue];
        }

        [animation setKeyTimes:times];
        [animation setValues:imageArray];
        [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
        animation.repeatCount = MAXFLOAT;   // 無限循環
        animation.duration    = totalTime;

        [[(UIImageView *)__self layer] addAnimation:animation forKey:@"gifAnimation"];
    }];
}

@end

這裡有兩個關鍵點:keyTimes 必須是 0~1 的比例值,所以要把每幀時間除以總時長做正規化;時間函式要設為 linear,否則會在每幀之間產生非預期的緩動。

2. 使用方式

- (void)showGifImageWithImageView {
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(112, 342, 132, 102)];
    NSURL *url = [[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] pathForResource:@"earthGif.gif" ofType:nil]];
    [imageView yh_setImage:url];
    [self.view addSubview:imageView];
}

第三方方案

1. YLGIFImage

專案位址:https://github.com/liyong03/YLGIFImage

#import "YLGIFImage.h"
#import "YLImageView.h"

- (void)showGifImageWithYLImageView {
    YLImageView *imageView = [[YLImageView alloc] initWithFrame:CGRectMake(112, 342, 132, 102)];
    CGFloat centerX = self.view.center.x;
    [imageView setCenter:CGPointMake(centerX, 402)];
    [self.view addSubview:imageView];

    imageView.image = [YLGIFImage imageNamed:@"earthGif.gif"];
}

用法幾乎與原生 UIImageView 相同,替換成本極低,適合成續把既有專案改成支援 GIF。

2. FLAnimatedImage

專案位址:https://github.com/Flipboard/FLAnimatedImage

- (void)showGifImageWithFLAnimatedImage {
    // 讀出 GIF 檔案
    NSString *pathForFile = [[NSBundle mainBundle] pathForResource:@"earthGif" ofType:@"gif"];
    NSData *dataOfGif = [NSData dataWithContentsOfFile:pathForFile];

    // 建立 FLAnimatedImage
    FLAnimatedImage *image = [FLAnimatedImage animatedImageWithGIFData:dataOfGif];

    // 搭配專用的 ImageView 顯示
    FLAnimatedImageView *imageView = [[FLAnimatedImageView alloc] init];
    imageView.animatedImage = image;
    imageView.frame = CGRectMake(112, 342, 132, 102);
    [self.view addSubview:imageView];
}

FLAnimatedImage 的重點在於它會把影格解碼後做緩存管理,在大量 GIF 或長列表場景下,記憶體表現明顯優於把每幀都解成 UIImage 的做法。

如何選擇

  • 只有一兩張 GIF、畫面單純:直接用 UIImageView + CAKeyframeAnimation,不引入額外套件。
  • 列表中有很多 GIF、需要控制記憶體:選 FLAnimatedImage,它的影格緩存機制就是為這個場景設計的。
  • 不想改動既有 UIImageView 用法:YLGIFImage 的替換成本最低。
  • 暫時不想寫任何程式:UIWebView 堪用,但要注意 WebView 本身的記憶體與啟動成本。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved