iOS加载GIF动画
程序员文章站
2022-03-24 18:37:09
...
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];
转载于:https://www.jianshu.com/p/6d757894ac97