基本上有三种方式来播放gif动画
1.webView播放方式
webView是一个很强大的控件,可以很容易的实现gif的播放,不过只能循环播放。
CGRect rect =CGRectMake(3,10,100,100);
rect.size = [UIImageimageNamed:@"jiafei.gif"].size;
_webView = [[UIWebViewalloc]initWithFrame:rect];
NSData *imgData = [NSDatadataWithContentsOfFile:[[NSBundlemainBundle]pathForResource:@"jiafei"ofType:@"gif"]];
[_webViewloadData:imgDataMIMEType:@"image/gif"textEncodingName:nilbaseURL:nil];
_webView.userInteractionEnabled =NO;//用不不可交互
_webView.backgroundColor = [UIColorclearColor];
_webView.opaque =NO;
[self.viewaddSubview:_webView];
//获取图片数据的格式的代码
+ (NSString *)MIMETypeForImageData:(NSData *)data {
if (!data)returnnil;
uint8_t c;
[datagetBytes:&clength:1];
switch (c) {
case0xFF:
return@"image/jpeg";
case0x89:
return@"image/png";
case0x47:
return@"image/gif";
case0x49:
case0x4D:
return@"image/tiff";
}
return nil;
}
2.第三方播放方式
采用ImageIO库,对gif文件进行解析,然后做动画显示
我觉得OLImageView写的不错,支持循环播放、暂停和继续播放,下载地址:http://code4app.com/ios/OLImageView/50beb9a26803fac635000001
注:需要导入两个库:ImageIO.framework 和 MobileCoreServices.framework
3.UIImageView播放方式
将gif分解成多张png图片,用UIImageView播放。
NSMutableArray *resourceArr = [[NSMutableArrayalloc]init];
for (int i =1;i <=17;i++)
{
UIImage *pic =nil;
if (i <10)
{
pic = [UIImageimageNamed:[NSStringstringWithFormat:@"campFire0%i.gif",i]];
}
else
{
pic = [UIImageimageNamed:[NSStringstringWithFormat:@"campFire%i.gif",i]];
}
[resourceArraddObject:pic];
}
UIImageView *fireImageView = [[UIImageViewalloc]initWithFrame:self.view.bounds];
fireImageView.animationImages = resourceArr;
//执行一次完整动画所需时长
fireImageView.animationDuration =1.75;
//repeat the animation forever
fireImageView.animationRepeatCount =0;
[fireImageViewstartAnimating];
[self.viewaddSubview:fireImageView];