改自swift版本: https://www.jianshu.com/p/0f39114a7f8e
首先导入<ImageIO/ImageIO.h>
创建imageview,然后:
// 1.获取CFDataRef类型
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"demo.gif" ofType:nil];
id fileData = [NSData dataWithContentsOfFile:filePath];
// 2.根据Data获取CGImageSource对象
CGImageSourceRef imageSource = CGImageSourceCreateWithData((CFDataRef)fileData, nil);
// 3.获取gif图片中图片的个数
NSIntegerframeCount = CGImageSourceGetCount(imageSource);
// 记录播放时间
float duration =0;
NSMutableArray *images = [NSMutableArray array];
for(inti =0; i < frameCount; i ++) {
// 3.1.获取图片
CGImageRef cgImage = CGImageSourceCreateImageAtIndex(imageSource, i, nil);
// 3.2.获取时长
CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil);
NSLog(@"%@",properties);
NSDictionary *gifInfo = (__bridgeNSDictionary*)properties;
duration = [gifInfo[@"{GIF}"][@"DelayTime"] doubleValue] + duration;
UIImage *image = [UIImage imageWithCGImage:cgImage];
[images addObject:image];
// 设置停止播放时显示的图片
if(i == frameCount -1) {
self.imageView.image = image;
}
}
// 4.播放图片
self.imageView.animationImages = images;
// 播放总时间
self.imageView.animationDuration = duration;
// 播放次数, 0为无限循环
self.imageView.animationRepeatCount = 1;
// 开始播放
[self.imageView startAnimating];
网友评论