iOS 播放gif動態圖的方式探討

來源:互聯網
上載者:User

標籤:

原文連結:http://my.oschina.net/u/2340880/blog/608560

 

摘要
iOS中沒有現成的介面來展示gif動態圖,但可以通過其他的方式來處理gif圖的展示。
iOS中播放gif動態圖的方式探討

一、引言

    在iOS開發中,UIImageView類專門來負責圖片資料的渲染,並且UIImageView也有幀動畫的方法來播放一組圖片,但是對於gif類型的資料,UIImageView中並沒有現成的介面提供給開發人員使用,在iOS中一般可以通過兩種方式來播放gif動態圖,一種方式是通過ImageIO架構中的方法將gif檔案中的資料進行解析,再使用coreAnimation核心動畫來播放gif動畫,另一種方式計較簡單,可以直接通過webView來渲染gif圖。

二、為原生的UIImageView添加類別來支援gif動態圖的播放

     gif動態圖檔案中包含了一組圖片及其資訊,資訊主要記錄著每一幀圖片播放的時間,我們如果擷取到了gif檔案中所有的圖片同時又擷取到每一幀圖片播放的時間,就可以為UIImageView添加核心動畫的方法來讓其播放gif的內容了。

    首先解析gif檔案中的資料,代碼如下:

//要引入ImageIO庫
#import <ImageIO/ImageIO.h>

//解析gif檔案資料的方法 block中會將解析的資料傳遞出來
-(void)getGifImageWithUrk:(NSURL *)url
               returnData:(void(^)(NSArray<UIImage *> * imageArray,
                                NSArray<NSNumber *>*timeArray,
                                CGFloat totalTime,
                                NSArray<NSNumber *>* widths,
                                NSArray<NSNumber *>* heights))dataBlock{
    //通過檔案的url來將gif檔案讀取為圖片資料引用
    CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)url, NULL);
    //擷取gif檔案中圖片的個數
    size_t count = CGImageSourceGetCount(source);
    //定義一個變數記錄gif播放一輪的時間
    float allTime=0;
    //存放所有圖片
    NSMutableArray * imageArray = [[NSMutableArray alloc]init];
    //存放每一幀播放的時間
    NSMutableArray * timeArray = [[NSMutableArray alloc]init];
    //存放每張圖片的寬度 (一般在一個gif檔案中,所有圖片尺寸都會一樣)
    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]];
        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);
}
為UIImageView添加一個設定gif圖內容的方法:

-(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;
            //設定每一幀的時間佔比
            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;
            //Layer層添加
            [[(UIImageView *)__self layer]addAnimation:animation forKey:@"gifAnimation"];
        }];
}
使用程式碼範例如下:

    UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0,0 , 320, 200)];
    NSURL * url = [[NSURL alloc]initFileURLWithPath:[[NSBundle mainBundle] pathForResource:imageName ofType:nil]];
    [imageView yh_setImage:url];
    [self.view addSubview:imageView];


三、使用UIWebView來載入gif動態圖資料

    iOS中的UIWebView功能十分強大,可以通過UIWebView為載體,來展示gif圖。並且這種方法也十分簡單,代碼如下:

         //讀取gif資料
         NSData *gifData = [NSData dataWithContentsOfURL:imageUrl];
        UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        //取消回彈效果
        webView.scrollView.bounces=NO;
        webView.backgroundColor = [UIColor clearColor];
        //設定縮放模式
        webView.scalesPageToFit = YES;
        //用webView載入資料
        [webView loadData:gifData MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];
四、兩種載入gif動態圖方式的優劣

    經過測試,從載入速度上來說,通過UIImageView類別載入的方式更加快速,UIWebView的方式載入時間會稍長,但是從效能上來比較,WebView的方式效能更優,播放的gif動態圖更加流暢。在開發中,可以根據需求,適當選擇,例如雖然WebView載入的方式效能更好,但是在許多情況下,原生的UIImageView能夠更加自由的讓開發人員進行擴充。

iOS 播放gif動態圖的方式探討

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.