iOS加载Gif图片的N种方式

1.系统UIImageView 多张图片组成动画

/**   *   UIImageView 动画   *   Memory-23M   */  

-(void)gifPlay1  { 

 //    NSArray  *array=@[@"image0.png",@"image1.png",@"image2.png"];  

//    UIImageView  *imgview= [UIImageView imageViewAnimation:CGRectMake(50,80, 550/2, 200)  imageNames:array duration:1];          

  UIImageView* animatedImageView = [[UIImageView alloc] initWithFrame:CGRectMake(50,80, 550/2, 200)];      animatedImageView.animationImages =@[[UIImage imageNamed:@"image0"],     [UIImage imageNamed:@"image1"],                                           [UIImage imageNamed:@"image2"]  ];     

 animatedImageView.animationDuration = 1.0f;      

animatedImageView.animationRepeatCount = 0;    

  [self.view addSubview: animatedImageView];     

 [animatedImageView startAnimating]; 

 }




2.利用第三方库

1)IImageView-PlayGIF  YFGIFImageView

/**   *  UIImageView-PlayGIF 是 UIImageView 子类,用来显示 GIF。UIIMageView-PlayGIF 性能高,而且占用的内存很低。 

  *  https://github.com/yfme/UIImageView-PlayGIF   *  Memory-21.9M   *  

#import "YFGIFImageView.h"  

 */  

-(void)gifPlay2  {  

    NSString  *gifPath=[[NSBundle mainBundle] pathForResource:@"test" ofType:@"gif"]; 

     YFGIFImageView  *gifview=[[YFGIFImageView alloc]init];    

  gifview.backgroundColor=[UIColor clearColor];  

    gifview.gifPath=gifPath;  

    gifview.frame=CGRectMake(50, 100,550/2, 200); 

     [self.view addSubview:gifview]; 

     [gifview startGIF]; 

 }


2)SCGIFImageView


/**   *  摘要: SCGIFImageView是一个开源的GIF图片动画显示控件,通过将GIF的每一帧都取出来生成UIImage对象存放在一个数组中,然后使用NSTimer进行动画轮转。   

*  https://github.com/shichangone/SCGifExample   *  Memory-22.5M   *

  #import "SCGIFImageView.h"   

*/

  -(void)gifPlay3  {  

    NSString* filePath = [[NSBundle mainBundle] pathForResource:@"test.gif" ofType:nil];  

    NSData* imageData = [NSData dataWithContentsOfFile:filePath];  

    SCGIFImageView* gifImageView = [[SCGIFImageView alloc]init];   

   [gifImageView setData:imageData];    

  gifImageView.frame = CGRectMake(50,100, gifImageView.image.size.width, gifImageView.image.size.height);      [self.view addSubview:gifImageView]; 

 }


3)YLGIFImage

/**   *  YLGIFImage 是异步 GIF 图像解码器和图像查看器,支持播放 GIF 图像,而且使用很少的内存。

   *  https://github.com/liyong03/YLGIFImage   *  Memory-22.7M   

* #import "YLImageView.h"   

*  #import "YLGIFImage.h"  

 */  

-(void)gifPlay5  {  

    YLImageView* imageView = [[YLImageView alloc] initWithFrame:CGRectMake(0, 160, 320, 240)]; 

     [self.view addSubview:imageView];   

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

}



4)SDWebImageView里的UIImage+GIF

提供接口:

+ (UIImage *)sd_animatedGIFNamed:(NSString *)name;

+ (UIImage *)sd_animatedGIFWithData:(NSData *)data;

- (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size;


/**   *  利用SDWebImageView 库播放gif   *  Memory-22.6M   * 

 #import "UIImage+GIF.h"  

 */ 

 -(void)gifPlay6  {  

    UIImage  *image=[UIImage sd_animatedGIFNamed:@"test"];     

 UIImageView  *gifview=[[UIImageView alloc]initWithFrame:CGRectMake(50,80,image.size.width, image.size.height)];      gifview.backgroundColor=[UIColor orangeColor];  

    gifview.image=image;

      [self.view addSubview:gifview];  

}

5)为MBProgressHUD 添加加载动画

/**   *  MBProgressHUD 添加加载动画   *  Memory-23.8M   * 

 #import "UIImage+GIF.h"  

 *  #import "MBProgressHUD.h"   

*/  

-(void)gifPlay6  {  

    UIImage  *image=[UIImage sd_animatedGIFNamed:@"test"];   

   UIImageView  *gifview=[[UIImageView alloc]initWithFrame:CGRectMake(0,0,image.size.width/2, image.size.height/2)];  

    gifview.image=image;        

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];    

  hud.color=[UIColor grayColor];//默认颜色太深了   

   hud.mode = MBProgressHUDModeCustomView;    

  hud.labelText = @"加载中...";    

  hud.customView=gifview; 

 }



3.为原生的UIImageView添加类别来支持gif动态图的播放

 gif动态图文件中包含了一组图片及其信息,信息主要记录着每一帧图片播放的时间,我们如果获取到了gif文件中所有的图片同时又获取到每一帧图片播放的时间,就可以为UIImageView添加核心动画的方法来让其播放gif的内容了。

   首先解析gif文件中的数据,代码如下:

//要引入ImageIO库

#import

//解析gif文件数据的方法 block中会将解析的数据传递出来

-(void)getGifImageWithUrk:(NSURL *)url

              returnData:(void(^)(NSArray * imageArray,

                               NSArray*timeArray,

                               CGFloat totalTime,

                               NSArray* widths,

                               NSArray* 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

       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 *imageArray, NSArray *timeArray, CGFloat totalTime, NSArray *widths, NSArray *heights) {

           //添加帧动画

           CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];

           NSMutableArray * times = [[NSMutableArray alloc]init];

           float currentTime = 0;

           //设置每一帧的时间占比

           for (int i=0; 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能够更加自由的让开发者进行扩展。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,198评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,663评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,985评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,673评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,994评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,399评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,717评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,407评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,112评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,371评论 2 241
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,891评论 1 256
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,255评论 2 250
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,881评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,010评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,764评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,412评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,299评论 2 260

推荐阅读更多精彩内容