ioscolorscgcontextcgcontextrefcgbitmapcontext

Replace specific color in CGBitmapContext


How can I replace specific color(RGB value) in CGBitmapContext that has already drawn?

Is there any easy way?

Thanks in advance.


Solution

  • You'll want to get a pointer to the pixels and information about their format by doing something like this:

    // 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++;
        }
    }