替换CGBitmapContext中的特定颜色

时间:2012-08-24 04:18:31

标签: ios colors cgcontext cgcontextref cgbitmapcontext

如何替换已绘制的CGBitmapContext中的特定颜色(RGB值)?

有简单的方法吗?

提前致谢。

1 个答案:

答案 0 :(得分:3)

您需要通过执行以下操作来获取指向像素的指针和有关其格式的信息:

// This assumes the data is RGBA format, 8-bits per channel. 
// You'll need to verify that by calling CGBitmapContextGetBitsPerPixel (), etc.
typedef struct RGBA8 {
    UInt8 red;
    UInt8 green;
    UInt8 blue;
    UInt8 alpha;
} RGBA8;

RGBA8* pixels = CGBitmapContextGetData (context);
UInt32 height = CGBitmapContextGetHeight (context);
UInt32 width = CGBitmapContextGetWidth (context);
UInt32 rowBytes = CGBitmapContextGetBytesPerRow (context);
UInt32 x, y;
for (y = 0; y < height; y++)
{
    RGBA8* currentRow = (RGBA8*)((UInt8*)pixels + y * rowBytes);
    for (x = 0; x < width; x++)
    {
        if ((currentRow->red == replaceRed) && (currentRow->green == replaceGreen) &&
            (currentRow->blue == replaceBlue) && (currentRow->alpha == replaceAlpha))
        {
            currentRow->red = newRed;
            currentRow->green = newGreen;
            currentRow->blue = newBlue;
            currentRow->alpha = newAlpha;
        }
        currentRow++;
    }
}