实际上,GIF动图文件中包含了一组图片及其信息数组,这些信息数据记录着这一组图片中各张图片的播放时长等信息,我们可以将图片和这些信息或取出来,使用UIImageView的帧动画技术进行动画播放。
好了不多说了 开始上代码吧:
首先自己找一个GIF图吧,拖到工程里面。
– (void)createGIF {
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 100, 280, 200)];
[self.view addSubview:imageView];
//1.找到gif文件路径
NSString *dataPath = [[NSBundle mainBundle]pathForResource:@”demo” ofType:@”gif”];
//2.获取gif文件数据
CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)[NSURL fileURLWithPath:dataPath], NULL);
//3.获取gif文件中图片的个数
size_t count = CGImageSourceGetCount(source);
//4.定义一个变量记录gif播放一轮的时间
float allTime = 0;
//5.定义一个可变数组存放所有图片
NSMutableArray *imageArray = [[NSMutableArray alloc] init];
//6.定义一个可变数组存放每一帧播放的时间
NSMutableArray *timeArray = [[NSMutableArray alloc] init];
//7.每张图片的宽度
NSMutableArray *widthArray = [[NSMutableArray alloc] init];
//8.每张图片的高度
NSMutableArray *heightArray = [[NSMutableArray alloc] init];
//遍历gif
for (size_t i=0; i<count; i++) {
CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);
[imageArray addObject__bridge UIImage *)(image)];
CGImageRelease(image);
//获取图片信息
NSDictionary *info = (__bridge NSDictionary *)CGImageSourceCopyPropertiesAtIndex(source, i, NULL);
NSLog(@”info—%@”,info);
//获取宽度
CGFloat width = [[info objectForKey__bridge NSString *)kCGImagePropertyPixelWidth] floatValue];
//获取高度
CGFloat height = [[info objectForKey__bridge NSString *)kCGImagePropertyPixelHeight] floatValue];
//
[widthArray addObject:[NSNumber numberWithFloat:width]];
[heightArray addObject:[NSNumber numberWithFloat:height]];
//统计时间
NSDictionary *timeDic = [info objectForKey__bridge NSString *)kCGImagePropertyGIFDictionary];
CGFloat time = [[timeDic objectForKey__bridge NSString *)kCGImagePropertyGIFDelayTime] floatValue];
[timeArray addObject:[NSNumber numberWithFloat:time]];
}
//添加帧动画
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@”contents”];
NSMutableArray *times = [[NSMutableArray alloc] init];
float currentTime = 0;
//设置每一帧的时间占比
for (int i=0; i<imageArray.count; i++) {
[times addObject:[NSNumber numberWithFloat:currentTime/allTime]];
currentTime +=[timeArray[i] floatValue];
}
[animation setKeyTimes:times];
[animation setValues:imageArray];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
//设置循环
animation.repeatCount = MAXFLOAT;
//设置播放总时长
animation.duration = allTime*MAXFLOAT;
//Layer层添加
[[imageView layer]addAnimation:animation forKey:@”gifAnimation”];
}
下面是我打印出来的信息:
好了,今天就到这里了,谢谢大家的支持。
参照:http://www.cnblogs.com/PengHongMiao/p/5897999.html
原创文章如转载请注明:
你必须 登录后 才能对文章进行评论!