我的项目中有一个GIF,我想在一个数组中获取GIF的所有图像。我正在使用它来创建图像视图并轻松制作动画。
- (UIImageView *)createImageViewWith:(NSData *)data frame:(CGRect)rect bAnimate:(BOOL)flag withAnimation:(BOOL)shouldAnimate {
CGImageSourceRef srcImage = CGImageSourceCreateWithData((__bridge CFTypeRef) data, nil);
if (!srcImage) {
NSLog(@"loading image failed");
}
size_t imgCount = CGImageSourceGetCount(srcImage);
NSTimeInterval totalDuration = 0;
NSNumber *frameDuration;
NSMutableArray *arrayImages;
arrayImages = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < imgCount; i ++) {
CGImageRef cgImg = CGImageSourceCreateImageAtIndex(srcImage, i, nil);
if (!cgImg) {
NSLog(@"loading %ldth image failed from the source", (long)i);
continue;
}
UIImage *img = [self scaledImage:[UIImage imageWithCGImage:cgImg] size:rect.size];
[arrayImages addObject:img];
NSDictionary *property = CFBridgingRelease(CGImageSourceCopyPropertiesAtIndex(srcImage, i, nil));
NSDictionary *gifDict = property[(__bridge id) kCGImagePropertyGIFDictionary];
frameDuration = gifDict[(__bridge id) kCGImagePropertyGIFUnclampedDelayTime];
if (!frameDuration) {
frameDuration = gifDict[(__bridge id) kCGImagePropertyGIFDelayTime];
}
totalDuration += frameDuration.floatValue;
CGImageRelease(cgImg);
}
if (srcImage != nil) {
CFRelease(srcImage);
}
UIImageView *imgView = [[UIImageView alloc] initWithFrame:rect];
imgView.image = arrayImages.firstObject;
imgView.autoresizingMask = 0B11111;
imgView.userInteractionEnabled = YES;
imgView.animationImages = arrayImages;
imgView.animationDuration = totalDuration;
imgView.animationRepeatCount = (flag == YES? 0 : 1);
if (shouldAnimate) {
[imgView startAnimating];
}
return imgView;
}
这段代码需要花费大量时间来获取图像并获得最终可用的图像视图。例如,此代码大约需要 4 秒来加载大约 120 张图像的 gif,这些图像在 4-5 秒内完全动画化。
有没有其他方法可以取出图像。谢谢。
有没有其他方法可以取出图像。
是的。
您可能想尝试第三方 GIF 解码器。例如,这个只不过是一个C/ObjC标头。只需将其包含在项目中,定义帧编写器回调并调用解码函数即可。