2017-06-14 39 views
1

我的项目中有一个GIF文件,我想要获取数组中的所有GIF图像。 我正在使用它来创建一个imageview和动画,在我的方便。如何从项目中的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张图像,该图像在4-5秒内完全生成动画。

是否有任何其他方式来获取图像。 谢谢。

回答

1

是否有任何其他方式获取图像。

是的。

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

+0

好的,谢谢我会试一试:) –

相关问题