如何从项目的GIF文件中获取图像

时间:2017-06-14 06:46:40

标签: ios objective-c image animated-gif

我的项目中有一个GIF,我想在阵列中获取GIF的所有图像。 我正在使用它来创建一个imageview并轻松制作动画。

- (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秒内完全显示。

还有其他方法可以拍摄出来。 谢谢。

1 个答案:

答案 0 :(得分:1)

  

还有其他方法可以拍摄出来。

您可能想尝试使用第三方GIF解码器。例如,This one只不过是一个C / ObjC标题。只需将它包含在项目中,定义一个帧编写器回调并调用解码函数。