iOS 加载gif动画相关代码如下
- (void)viewDidLoad {
[super viewDidLoad];
// 先引用ImageIO 获取gifSource #import <ImageIO/ImageIO.h>
NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:@"jiafei" withExtension:@"gif"];
CGImageSourceRef gifSource = CGImageSourceCreateWithURL((CFURLRef)fileUrl, NULL);
size_t imageCount = CGImageSourceGetCount(gifSource);
NSMutableArray *images = [[NSMutableArray alloc] initWithCapacity:imageCount];
NSMutableArray *times = [[NSMutableArray alloc] initWithCapacity:imageCount];
NSMutableArray *keyTimes = [[NSMutableArray alloc] initWithCapacity:imageCount];
float totalTime = 0;
for (size_t i = 0; i < imageCount; i++) {
CGImageRef cgimage= CGImageSourceCreateImageAtIndex(gifSource, i, NULL);
[images addObject:(__bridge id)cgimage];
CGImageRelease(cgimage);
NSDictionary *properties = (__bridge NSDictionary *)CGImageSourceCopyPropertiesAtIndex(gifSource, i, NULL);
NSDictionary *gifProperties = [properties valueForKey:(__bridge NSString *)kCGImagePropertyGIFDictionary];
NSString *gifDelayTime = [gifProperties valueForKey:(__bridge NSString* )kCGImagePropertyGIFDelayTime];
[times addObject:gifDelayTime];
totalTime += [gifDelayTime floatValue];
// _size.width = [[properties valueForKey:(NSString*)kCGImagePropertyPixelWidth] floatValue];
// _size.height = [[properties valueForKey:(NSString*)kCGImagePropertyPixelHeight] floatValue];
}
float currentTime = 0;
for (size_t i = 0; i < times.count; i++) {
float keyTime = currentTime / totalTime;
[keyTimes addObject:[NSNumber numberWithFloat:keyTime]];
currentTime += [[times objectAtIndex:i] floatValue];
}
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
[animation setValues:images];
[animation setKeyTimes:keyTimes];
animation.duration = totalTime;
animation.repeatCount = HUGE_VALF;
[self.view.layer addAnimation:animation forKey:@"gifAnimation"];
}