我想限制動畫GIF(從數組CGImageRef
創建)的顏色數。核心圖形和GIF顏色表
但是,我很難實際設置自定義顏色表。有誰知道如何用Core Graphics來做到這一點?我知道的kCGImagePropertyGIFImageColorMap
。以下是一些測試代碼(從this github gist大量借用 - 因爲它是Google可以找到的唯一的kCGImagePropertyGIFImageColorMap
實例)。
NSString *path = [@"~/Desktop/test.png" stringByExpandingTildeInPath];
CGDataProviderRef imgDataProvider = CGDataProviderCreateWithCFData((CFDataRef)[NSData dataWithContentsOfFile:path]);
CGImageRef image = CGImageCreateWithPNGDataProvider(imgDataProvider, NULL, true, kCGRenderingIntentDefault);
const uint8_t colorTable[ 8 ] = { 0, 0, 0, 0, 255, 255, 255 , 255};
NSData* colorTableData = [ NSData dataWithBytes: colorTable length: 8 ];
NSMutableDictionary *gifProps = [NSMutableDictionary dictionary];
[gifProps setObject:colorTableData forKey:(NSString *)kCGImagePropertyGIFImageColorMap];
[gifProps setObject:[NSNumber numberWithBool:NO] forKey:(NSString *)kCGImagePropertyGIFHasGlobalColorMap];
NSDictionary* imgProps = [ NSDictionary dictionaryWithObject: gifProps
forKey: (NSString*) kCGImagePropertyGIFDictionary ];
NSURL* destUrl = [NSURL fileURLWithPath:[@"~/Desktop/test.gif" stringByExpandingTildeInPath]];
CGImageDestinationRef dst = CGImageDestinationCreateWithURL((CFURLRef) destUrl, kUTTypeGIF, 1, NULL);
CGImageDestinationAddImage(dst, image, imgProps);
CGImageDestinationSetProperties(dst, (CFDictionaryRef) imgProps);
CGImageDestinationFinalize(dst);
CFRelease(dst);
但是,這並不會產生黑色的&白色圖像。
此外,我試過打開一個GIF來查找顏色表信息,但這只是提供了一點幫助。
CGImageSourceRef imageSourceRef = CGImageSourceCreateWithURL((CFURLRef) destUrl, NULL);
NSDictionary *dict = (NSDictionary *)CGImageSourceCopyPropertiesAtIndex(imageSourceRef,0, NULL);
CGImageRef img = CGImageSourceCreateImageAtIndex(imageSourceRef, 0, NULL);
printf("Color space model: %d, indexed=%d, rgb = %d\n", CGColorSpaceGetModel(CGImageGetColorSpace(img)), kCGColorSpaceModelIndexed,kCGColorSpaceModelRGB);
NSLog(@"%@", dict);
它說色彩空間是GIF的RGB。然而,如果我用索引的PNG嘗試這個代碼,它說色彩空間是索引的。
此外,所有我已經試過的GIF有一個像字典,看起來大致如下所示:
{
ColorModel = RGB;
Depth = 8;
HasAlpha = 1;
PixelHeight = 176;
PixelWidth = 314;
"{GIF}" = {
DelayTime = "0.1";
UnclampedDelayTime = "0.04";
};
}
(如果我使用CGImageSourceCopyProperties(...)
,它提到一個全球性的彩色地圖,但同樣沒有顏色表提供)。
在標籤中說OS X。 – uchuugaka 2015-01-20 04:46:40