您的位置:首页 > 移动开发 > IOS开发

iOS 加载gif动画

2016-02-22 15:38 351 查看
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"];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: