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

iOS 上播放 GIF 的四種方案:UIWebView、UIImageView 與兩款開源庫

編輯:iOS 開發綜合

UIImage 天生不支援 GIF 動畫,要在 App 裡播放 GIF,實務上大概有四條路。以下從「系統原生」到「第三方庫」逐一說明各自的取捨。

方案一:UIWebView

把 GIF 資料丟給 WebView,讓系統自己去解碼播放。

特性:載入起步稍慢,但整體效能與流暢度最好,複雜的多幀 GIF 也不容易掉幀。

- (void)showGifImageWithWebView {
    NSData *gifData = [NSData dataWithContentsOfFile:
        [[NSBundle mainBundle] pathForResource:@"earthGif" ofType:@"gif"]];

    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(112, 302, 132, 102)];
    webView.userInteractionEnabled = NO;
    [webView loadData:gifData MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];

    [self.view addSubview:webView];
}

方案二:UIImageView + ImageIO 自行解幀

做法是先用 ImageIO 把 GIF 拆成一張張 UIImage 與對應的時間,再用 CAKeyframeAnimation 播放。

特性:載入速度快,畫面可控性高,但效能不如 WebView,且程式碼量最大。優點是易於擴充——你可以自行決定播放次數、要不要快取解碼結果等。

先為 UIImageView 寫一個分類,對外只暴露兩個方法:

@interface UIImageView (Tool)

/** 解析 GIF 資料,透過 block 把結果回傳出來 */
- (void)getGifImageWithUrl:(NSURL *)url
                returnData:(void(^)(NSArray *imageArray,
                                     NSArray *timeArray,
                                     CGFloat totalTime,
                                     NSArray *widths,
                                     NSArray *heights))dataBlock;

/** 直接為 UIImageView 設定 GIF 內容 */
- (void)yh_setImage:(NSURL *)imageUrl;

@end

實作的核心是走訪 CGImageSource 的每一幀,取出影像與 duration:

#import <ImageIO/ImageIO.h>

- (void)getGifImageWithUrl:(NSURL *)url
                returnData:(void(^)(NSArray *, NSArray *, CGFloat, NSArray *, NSArray *))dataBlock {
    CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)url, NULL);
    size_t count = CGImageSourceGetCount(source);

    float allTime = 0;
    NSMutableArray *imageArray  = [NSMutableArray array];
    NSMutableArray *timeArray   = [NSMutableArray array];
    NSMutableArray *widthArray  = [NSMutableArray array];
    NSMutableArray *heightArray = [NSMutableArray array];

    for (size_t i = 0; i < count; i++) {
        CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);
        NSDictionary *info = (__bridge NSDictionary *)CGImageSourceCopyPropertiesAtIndex(source, i, NULL);
        NSDictionary *timeDic = [info objectForKey:@"GIFDictionary"];

        CGFloat width  = [[timeDic objectForKey:@"Width"]  floatValue];
        CGFloat height = [[timeDic objectForKey:@"Height"] floatValue];
        CGFloat time   = [[timeDic objectForKey:@"DelayTime"] floatValue];

        [widthArray  addObject:[NSNumber numberWithFloat:width]];
        [heightArray addObject:[NSNumber numberWithFloat:height]];
        [timeArray   addObject:[NSNumber numberWithFloat:time]];
        [imageArray  addObject:[UIImage imageWithCGImage:image]];

        allTime += time;
        CGImageRelease(image);
    }

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

拿到資料後,用 CAKeyframeAnimation 依每幀的時間佔比驅動:

- (void)yh_setImage:(NSURL *)imageUrl {
    [self getGifImageWithUrl:imageUrl returnData:^(NSArray *imageArray,
                                                  NSArray *timeArray,
                                                  CGFloat totalTime,
                                                  NSArray *widths,
                                                  NSArray *heights) {
        CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
        NSMutableArray *times = [NSMutableArray array];
        float currentTime = 0;

        for (NSNumber *t in timeArray) {
            currentTime += [t floatValue];
            [times addObject:[NSNumber numberWithFloat:currentTime / totalTime]];
        }

        animation.duration    = totalTime;
        animation.repeatCount = MAXFLOAT;
        animation.values      = imageArray;
        animation.keyTimes    = times;
        animation.calculationMode = kCAAnimationDiscrete;

        [self.layer addAnimation:animation forKey:@"gif"];
        self.layer.contents = (__bridge id)(imageArray.firstObject.CGImage);
    }];
}

使用時:

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

方案三:YLGIFImage

開源位址:https://github.com/liyong03/YLGIFImage

它提供一組 YLImageView,把解碼與播放都封裝好,替換成本極低——只要把 UIImageView 換成 YLImageView,再把 image 設成 YLGIFImage 即可。

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

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

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

方案四:FLAnimatedImage

開源位址:https://github.com/Flipboard/FLAnimatedImage

由 Flipboard 出品,在記憶體管理上做得相當講究:它會把解碼後的畫面做一個有上限的快取池,而不是像某些實作那樣把整份 GIF 的所有幀全部解成 UIImage 常駐記憶體。播放大型 GIF 時,這是它最大的優勢。

- (void)showGifImageWithFLAnimatedImage {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"earthGif" ofType:@"gif"];
    NSData *data = [NSData dataWithContentsOfFile:path];

    FLAnimatedImage *image = [FLAnimatedImage animatedImageWithGIFData:data];
    FLAnimatedImageView *imageView = [[FLAnimatedImageView alloc] init];
    imageView.animatedImage = image;
    imageView.frame = CGRectMake(112, 342, 132, 102);

    [self.view addSubview:imageView];
}

該選哪一個?

如果只是一張裝飾性的小 GIF,用 WebView 最省事;如果在列表裡大量播放、對記憶體敏感,FLAnimatedImage 是最穩的選擇;如果需要完全掌控播放行為(暫停、倍速、指定幀),就走 ImageIO 自製那條路。

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