在iOS开发中经常会遇到加载动态图,下面来谈谈,在项目中加载动态图的常用方式。
利用UIImageView实现简单的帧动画
NSMutableArray * imgsArr = [NSMutableArray array];
for (int i=0; i<7; i++) {
NSString *str = [NSString stringWithFormat:@"0%d.jpg",i+1];
[imgsArr addObject:[UIImage imageNamed:str]];
}
UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
[imageView setAnimationImages:imgsArr];
[imageView setAnimationDuration:1];//设置时间
imageView.animationRepeatCount = 0;//设置次数
[imageView startAnimating];//开始执行
[self.view addSubview:imageView];
复制代码
效果如下:
SDWebImage加载gif图片
需要先导入文件 #import <UIImage+GIF.h>
但是用SDWebImage去加载缓存图片,会出现内存增多,SDWebImage 对多gif显示内存消耗过高,需要优化一下,推荐看看这篇文章,这篇文章就优化的很好。
UIImageView *gifImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
NSString *path = [[NSBundle mainBundle] pathForResource:@"2" ofType:@"gif"];
NSData *data = [NSData dataWithContentsOfFile:path];
UIImage *image = [UIImage sd_animatedGIFWithData:data];
gifImageView.image = image;
[self.view addSubview:gifImageView];
复制代码
WKWebView加载gif图片
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:webView];
NSURL *url = [NSURL URLWithString:@"https://xxxxxx"];
[webView loadRequest:[NSURLRequest requestWithURL:url]];
复制代码
UIWebView和WKWebView使用差别不大,加载本地的动图的时候用pathForResource。常用的就是这三种方式加载动图,就是使用SDWebImage的时候要考虑到内存的问题,需要优化。 本文图片借鉴于这篇文章