xavoDev
xavoDev

Reputation: 51

Changing the color of a pixel

i am able to read a particular pixel at given CGPoint but i have been looking to change the color of a pixel and it would be highly appreciated if anyone can help me out with a code snippet.

My Code is:

unsigned char* data = CGBitmapContextGetData (cgctx);       

if (data != NULL) {    
  offset = 4*((w*round(point.y))+round(point.x));    
  alpha =  data[offset];     
  red = data[offset+1];             
  green = data[offset+2];           
  blue = data[offset+3];     
  color = [UIColor colorWithRed:(red/255.0f) 
                   green:(green/255.0f) blue:(blue/255.0f) 
                   alpha:(alpha/255.0f)];       
}

Upvotes: 1

Views: 923

Answers (1)

Mark
Mark

Reputation: 6128

It's not clear what you are trying to do. If you want to change the pixel's color in the original CGImageRef then you would use something like:


// Set the color of the pixel to 50% grey + 50% alpha
data[offset+0] = 128;
data[offset+1] = 128;
data[offset+2] = 128;
data[offset+3] = 128;

// Create a CGBitmapImageContext 
CGContextRef bitmapContext = CGBitmapContextCreate(data, width, height, CGImageGetBitsPerComponent(), width * 4, CGImageGetColorSpace(), kCGImageAlphPremultipliedFirst);

// Draw the bitmap context back to your original context
CGContextDrawImage(bitmapContext, CGMakeRect(...), cgctx); 

You should make all of your changes to the data* at once and then write the modified bitmap buffer back to the original context.

Upvotes: 1

Related Questions