iOS之加载Gif图片的方法

2020-01-21 02:36:52刘景俊

Gif图片是非常常见的图片格式,尤其是在聊天的过程中,Gif表情使用地很频繁。但是iOS竟然没有现成的支持加载和播放Gif的类。

简单地汇总了一下,大概有以下几种方法:

一、加载本地Gif文件

1、使用UIWebView


  // 读取gif图片数据 
  UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,200,200)];
  [self.view addSubview:webView];

  NSString *path = [[NSBundle mainBundle] pathForResource:@"001" ofType:@"gif"];
  /*
     NSData *data = [NSData dataWithContentsOfFile:path];
     使用loadData:MIMEType:textEncodingName: 则有警告
     [webView loadData:data MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];
   */
  NSURL *url = [NSURL URLWithString:path];
  [webView loadRequest:[NSURLRequest requestWithURL:url]];

但是使用UIWebView的弊端在于,不能设置Gif动画的播放时间。

2、将Gif拆分成多张图片,使用UIImageView播放

最好把所需要的Gif图片打包到Bundle文件内,如下图所示

iOS,加载Gif图片,ios加载本地gif图片,ios加载gif


- (NSArray *)animationImages
{
  NSFileManager *fielM = [NSFileManager defaultManager];
  NSString *path = [[NSBundle mainBundle] pathForResource:@"Loading" ofType:@"bundle"];
  NSArray *arrays = [fielM contentsOfDirectoryAtPath:path error:nil];
  
  NSMutableArray *imagesArr = [NSMutableArray array];
  for (NSString *name in arrays) {
    UIImage *image = [UIImage imageNamed:[(@"Loading.bundle") stringByAppendingPathComponent:name]];
    if (image) {
      [imagesArr addObject:image];
    }
  }
  return imagesArr;
}

- (void)viewDidLoad {
  [super viewDidLoad];
  
  UIImageView *gifImageView = [[UIImageView alloc] initWithFrame:frame];
  gifImageView.animationImages = [self animationImages]; //获取Gif图片列表
  gifImageView.animationDuration = 5;   //执行一次完整动画所需的时长
  gifImageView.animationRepeatCount = 0; //动画重复次数
  [gifImageView startAnimating];
  [self.view addSubview:gifImageView];
}

3、使用SDWebImage

但是很遗憾,SDWebImage 的 sd_setImageWithURL:placeholderImage:这个方法是不能播放本地Gif的,它只能显示Gif的第一张图片而已。So,此方法行不通


  UIImageView *gifImageView = [[UIImageView alloc] initWithFrame:frame];
  [gifImageView sd_setImageWithURL:nil placeholderImage:[UIImage imageNamed:@"gifTest.gif"]];

其实,在SDWebImage这个库里有一个UIImage+GIF的类别,里面为UIImage扩展了三个方法:


@interface UIImage (GIF)
+ (IImage *)sd_animatedGIFNamed:(NSString *)name;
+ (UIImage *)sd_animatedGIFWithData:(NSData *)data;
- (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size;
@end