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秒內完全生成動畫。
是否有任何其他方式來獲取圖像。 謝謝。
好的,謝謝我會試一試:) –