当我们网络加载GIF,或者获取到本地GIF的数据data时,可以将data转换成动图UIImage
//获取动图
+ (UIImage *)animatedGIFWithData:(NSData *)data {
if(!data) {
return nil;
}
//获取动图源数据
CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
//获取动图图片集数量
size_t count = CGImageSourceGetCount(source);
UIImage * animatedImage;
//如果图片集只有一张,那么直接创建成一张图片,否则合成一个动图
if(count <=1) {
animatedImage = [[UIImage alloc]initWithData:data];
}else {
NSMutableArray * images = [NSMutableArray array];
//记录动图总时长
NSTimeInterval duration =0.0f;
//遍历每张图片
for(size_t i =0; i < count; i++) {
CGImageRef image =CGImageSourceCreateImageAtIndex(source, i,NULL);
//获取单张动图时间间距
duration += [self frameDurationAtIndex:i source:source];
[images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]];
CGImageRelease(image);
}
//若未获取到时长,,自定义时长为0.1x张数,,这里可以根据需求自定义
if(!duration) {
duration = (1.0f/10.0f) * count;
}
//创建动图
animatedImage = [UIImage animatedImageWithImages:images duration:duration];
}
CFRelease(source);
return animatedImage;
}
+ (float)frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source {
float frameDuration =0.1f;
CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index,nil);
NSDictionary * frameProperties = (__bridgeNSDictionary*)cfFrameProperties;
NSDictionary * gifProperties = frameProperties[(NSString*)kCGImagePropertyGIFDictionary];
NSNumber * delayTimeUnclampedProp = gifProperties[(NSString*)kCGImagePropertyGIFUnclampedDelayTime];
if(delayTimeUnclampedProp) {
frameDuration = [delayTimeUnclampedProp floatValue];
}
else{
NSNumber * delayTimeProp = gifProperties[(NSString*)kCGImagePropertyGIFDelayTime];
if(delayTimeProp) {
frameDuration = [delayTimeProp floatValue];
}
}
CFRelease(cfFrameProperties);
return frameDuration;
}