Mouhamad Lamaa Mouhamad Lamaa - 1 year ago 116
Objective-C Question

Objective-C / iphone - change Pixel Colour?

the aim of my project: user can change the color of a part to images by touching the screen, when he touch any area the color of this area should be changed

i have many ideas but my ideas are based on placing another images (created dynamically) in the view, but these ideas are memory expensive;

how to do this ().

Answer Source

You can use Core Graphics. Add QuartzCore framework to your project.

The basic way to do this is to render your image in a bitmap context :

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef bmContext = CGBitmapContextCreate(NULL, width, height, 8,bytesPerRow, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);
CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = originalWidth, .size.height = originalHeight}, cgImage);

then you can grab a reference to the underlying pixels :

UInt8* data = (UInt8*)CGBitmapContextGetData(bmContext);

Then do pixels operation :

const size_t bitmapByteCount = bytesPerRow * originalHeight;
for (size_t i = 0; i < bitmapByteCount; i += 4)
    UInt8 a = data[i];
    UInt8 r = data[i + 1];
    UInt8 g = data[i + 2];
    UInt8 b = data[i + 3];

    // Do pixel operation here

    data[i] = (UInt8)newAlpha
    data[i + 1] = (UInt8)newRed;
    data[i + 2] = (UInt8)newGreen;
    data[i + 3] = (UInt8)newBlue;

Finally grab your new image from the context :

CGImageRef newImage = CGBitmapContextCreateImage(bmContext);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download