当GIF具有大量帧时,Xcode GIF输出颜色失真

时间:2014-07-23 08:56:49

标签: ios xcode gif

我使用以下代码在xcode中创建GIF:

NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
NSURL *fileURL = [documentsDirectoryURL URLByAppendingPathComponent:@"animated.gif"];
CGImageDestinationRef destination = CGImageDestinationCreateWithURL((__bridge CFURLRef)fileURL, kUTTypeGIF, imageArray.count, NULL);

NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:5];

NSDictionary *frameProperties = [NSDictionary dictionaryWithObject:dict forKey:(NSString *)kCGImagePropertyPNGDictionary];

NSMutableDictionary *dict2 = [NSMutableDictionary dictionaryWithCapacity:5];

const uint8_t colorTable2[9] = {0, 0, 0, 128, 128, 128, 255,255,255};
NSData *colorTableData2 = [NSData dataWithBytes:colorTable2 length:9];

[dict2 setObject:colorTableData2 forKey:(NSString *)kCGImagePropertyGIFImageColorMap];
[dict2 setObject:[NSNumber numberWithInt:0] forKey:(NSString *)kCGImagePropertyGIFLoopCount];
[dict2 setObject:[NSNumber numberWithFloat:0.005] forKey:(NSString *)kCGImagePropertyGIFDelayTime];

NSDictionary *gifProperties = [NSDictionary dictionaryWithObject:dict2 forKey:(NSString *) kCGImagePropertyGIFDictionary];

for (int i = 0; i < imageArray.count; i++) {
    UIImage *image = [UIImage imageWithContentsOfFile:[imageArray objectAtIndex:i]];
    CGImageDestinationAddImage(destination, image.CGImage, (__bridge CFDictionaryRef)frameProperties);
}

CGImageDestinationSetProperties(destination, (__bridge CFDictionaryRef)gifProperties);
CGImageDestinationFinalize(destination);
CFRelease(destination);

这里的问题是如果imageArray.count小于23,输出GIF将不包含颜色失真。如果它大于22,则颜色失真将以图像的色块形式出现,采用背景色而不是原始色。

我认为我没有设置任何代码来执行图像压缩,因此我不确定为什么会发生这种情况。如果有人能够对这个问题提供一些见解,那将对我有很大帮助。

编辑: 我保存了每个单独的框架,以确保颜色失真不是由于框架本身造成的。因此我觉得它与CG框架有关。

感谢。

1 个答案:

答案 0 :(得分:0)

尝试使用ImageIO.framework框架在iOS APP中使用GIF,我的GIF图像也变得扭曲,但后来我使用了这种方法,它们很好

NSURL *url1 = [[NSBundle mainBundle] URLForResource:@"YourImage" withExtension:@"gif"];

self.imageView.image = [UIImage animatedImageWithAnimatedGIFData:[NSData dataWithContentsOfURL:url1]];

他们在这之后很好。