在UIImage(或其衍生物)中,如何将一种颜色替换为另一种颜色?

Oli*_*lie 2 iphone colors uiimage

例如,我有一个UIImage(如果需要,我可以从中获取CGImage,CGLayer等),我想用蓝色(0,0,1)替换所有红色像素(1,0,0) ).

我有代码来确定哪些像素是目标颜色(请参阅此SO问题和答案),我可以替换rawData中的相应值,但(a)我不知道如何从我的rawData缓冲区返回UIImage (b)似乎我可能会错过一个内置的,它将自动为我完成所有这些,为我节省了大量的悲伤.

谢谢!

Oli*_*lie 9

好的,所以我们将UIImage放入rawBits缓冲区(参见原始问题中的链接),然后我们将缓冲区中的数据调整到我们的喜好(即,将所有红色组件(每4个字节)设置为0,作为测试),现在需要获得一个代表twiddled数据的新UIImage.

我在Erica Sudan的iPhone Cookbook,第7章(图像),例12(Bitmaps)中找到了答案.相关调用是CGBitmapContextCreate(),相关代码是:

+ (UIImage *) imageWithBits: (unsigned char *) bits withSize: (CGSize)  
size
{
    // Create a color space
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    if (colorSpace == NULL)
    {
        fprintf(stderr, "Error allocating color space\n");
        free(bits);
        return nil;
    }

    CGContextRef context = CGBitmapContextCreate (bits, size.width,  
size.height, 8, size.width * 4, colorSpace,  
kCGImageAlphaPremultipliedFirst);
    if (context == NULL)
    {
        fprintf (stderr, "Error: Context not created!");
        free (bits);
        CGColorSpaceRelease(colorSpace );
        return nil;
    }

    CGColorSpaceRelease(colorSpace );
    CGImageRef ref = CGBitmapContextCreateImage(context);
    free(CGBitmapContextGetData(context));
    CGContextRelease(context);

    UIImage *img = [UIImage imageWithCGImage:ref];
    CFRelease(ref);
    return img;
}
Run Code Online (Sandbox Code Playgroud)

希望这对未来的网站探险者有用!