如何使用CGImageCreateWithMaskingColors应用多个颜色蒙版?

时间:2011-02-08 04:39:20

标签: xcode quartz-2d masking

我对Objective-c有点新,甚至更新的Quartz 2D编程,所以提前道歉!我有一个方法,我想从UIImage中删除一些特定的颜色(不只是一个)。

当我使用一个颜色蒙版运行我的项目时,它工作得很漂亮。一旦我尝试堆叠它们,'whiteRef'就会出现NULL。我甚至尝试修改我的方法来采用颜色蒙版,然后简单地运行我的方法两次 - 使用不同颜色的面具 - 但仍然没有。

非常感谢任何帮助!

- (UIImage *)doctorTheImage:(UIImage *)originalImage
{
    const float brownsMask[6] = {124, 255, 68, 222, 0, 165};
    const float whiteMask[6] = {255, 255,  255, 255, 255, 255};

    UIImageView *imageView = [[UIImageView alloc] initWithImage:originalImage];

    UIGraphicsBeginImageContext(originalImage.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGImageRef brownRef = CGImageCreateWithMaskingColors(imageView.image.CGImage, brownsMask);    
    CGImageRef whiteRef = CGImageCreateWithMaskingColors(brownRef, whiteMask);    
    CGContextDrawImage (context, CGRectMake(0, 0, imageView.image.size.width, imageView.image.size.height), whiteRef);

    CGImageRelease(brownRef);
    CGImageRelease(whiteRef);

    UIImage *doctoredImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [imageView release];

    return doctoredImage;
}

1 个答案:

答案 0 :(得分:1)

嗯,我找到了一个好的工作!基本上,我最终在MKMapView上使用了图像数据,所以我需要做的就是将图像分解为像素,从那里我可以随意乱搞。它可能不是速度方面的最佳选择,但可以解决问题。以下是我正在使用的代码示例。

//Split the images into pixels to mess with the image pixel colors individually
size_t bufferLength = gridWidth * gridHeight * 4;
unsigned char *rawData = nil;
rawData = (unsigned char *)[self convertUIImageToBitmapRGBA8:myUIImage];

grid = malloc(sizeof(float)*(bufferLength/4));

NSString *hexColor = nil;

for (int i = 0 ; i < (bufferLength); i=i+4)
{
hexColor = [NSString stringWithFormat: @"%02x%02x%02x", (int)(rawData[i + 0]),(int)(rawData[i + 1]),(int)(rawData[i + 2])];


//mess with colors how you see fit - I just detected certain colors and slapped 
//that into an array of floats which I later put over my mapview much like the 
//hazardmap example from apple.

if ([hexColor isEqualToString:@"ff0299"]) //pink
    value = (float)11;
if ([hexColor isEqualToString:@"9933cc"]) //purple
    value = (float)12;

//etc...

grid[i/4] = value;
}

我还从这里借用了一些方法(即:convertUIImageToBitmapRGBA8):https://gist.github.com/739132

希望这可以帮助别人!