gif动画效果实现方式

gif 图片的展示方式有几种:webView方法、逐桢展示、第三方

webView展示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//获取gif图片的尺寸
CGRect frame = CGRectZero;

//图片可以是jpg格式,也可能是gif格式
frame.size = [UIImage imageNamed:@"x.jpg"].size;

// 读取gif图片数据
NSData gif = [NSData dataWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"x" ofType:@"jpg"]];
UIWebView *webView = [[UIWebView alloc] initWithFrame:frame];

/*这里注意:如果不用上面获取的gif图片的尺寸,而是自定义view的frame,当设置的frame小于gif本身的尺寸大小时,图片展示时不像UIImageView那样自动 缩放,而是只展示gif的一部分。另外,当frame的宽度是整个屏幕宽度,x坐标从0开始,如果gif的尺寸大于屏幕宽度,gif的展示将按gif图本身的宽高比展示。假设gif尺寸为(500,300),屏幕尺寸为(320,568),如果frame的x,y都为0,gif的展示为(0,0,320,320/500.0*300)*/

webView.userInteractionEnabled = NO;

/*中间设置的type类型一定要有image/xxx,后面的xxx可以是png、jpg、gif,即使gif的格式是jpg也没关系*/
[webView loadData:gif MIMEType:@"image/jpg" textEncodingName:nil baseURL:nil];

[self.view addSubview:webView];

逐桢展示(animation效果)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
   UIImageView *gifView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 0, self.view.frame.size.width - 40,300)];
NSMutableArray *gifArray = [[NSMutableArray alloc] initWithCapacity:20];
for (NSInteger i = 0; i < 20; i++) {
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%ld.jpg",(long)i]];
[gifArray addObject:image];
}
gifView.image = gifArray.lastObject;

/*注意这个数组里存放的数据类型是UIImage*/
gifView.animationImages = gifArray;

/* 一个动画循环的时间 */
gifView.animationDuration = 10;

/*动画重复次数,0表示无限循环*/
gifView.animationRepeatCount = 0;
[gifView startAnimating];
/*需要触发停止动画时可用[gifView stopAnimating];*/
[self.view addSubview:gifView];

第三方

貌似有不少第三方,这个OLImage这个用起来还是挺简单的,而且图片的大小是铺满的填充效果。gitHub地址:https://github.com/dtorres/OLImageView
在当前controller或view中导入OLImageView.h和OLImage.h两个头文件即可

1
2
3
4
5
6
   self.gifView = [[OLImageView alloc] initWithFrame:CGRectMake(0, 100, 300, 300)];
self.gifView.center = self.view.center;
NSString *imgPath = [[NSBundle mainBundle] pathForResource:@"x" ofType:@"jpg"];/*gif图路径*/
/*NSData转为UIImage*/
self.gifView.image = [OLImage  imageWithData:data];
[self.view addSubview:self.gifView];