iOS加载GIF动画
2018-06-01 本文已影响167人
Moker_C
1、使用webView加载
NSString *path = [[NSBundle mainBundle] pathForResource:@"refreshing01" ofType:@"gif"];
NSData *gifData = [NSData dataWithContentsOfFile:path];
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(kSCREEN_WIDTH*0.5-15, 15, 30, 30)];
webView.scalesPageToFit = YES;
[webView loadData:gifData MIMEType:@"image/gif" textEncodingName:@"" baseURL:[NSURL URLWithString:@""]];
webView.backgroundColor = [UIColor clearColor];
webView.opaque = NO;
[self.view addSubview:webView];
2、使用ImageView加载
//将GIF图片分解成多张PNG图片
//得到GIF图片的url
NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:@"refreshing01" withExtension:@"gif"];
//将GIF图片转换成对应的图片源
CGImageSourceRef gifSource = CGImageSourceCreateWithURL((CFURLRef) fileUrl, NULL);
//获取其中图片源个数,即由多少帧图片组成
size_t frameCount = CGImageSourceGetCount(gifSource);
//定义数组存储拆分出来的图片
NSMutableArray *frames = [[NSMutableArray alloc] init];
for (size_t i = 0; i < frameCount; i++) {
//从GIF图片中取出源图片
CGImageRef imageRef = CGImageSourceCreateImageAtIndex(gifSource, i, NULL);
//将图片源转换成UIimageView能使用的图片源
UIImage *imageName = [UIImage imageWithCGImage:imageRef];
//将图片加入数组中
[frames addObject:imageName];
CGImageRelease(imageRef);
}
UIImageView *gifImageView = [[UIImageView alloc] initWithFrame:CGRectMake(kSCREEN_WIDTH*0.5-15, 15, 30, 30)];
//将图片数组加入UIImageView动画数组中
gifImageView.animationImages = frames;
//每次动画时长
gifImageView.animationDuration = 1.3;
//开启动画,此处没有调用播放次数接口,UIImageView默认播放次数为无限次,故这里不做处理
[gifImageView startAnimating];
[self.view addSubview:gifImageView];