I am using GraphicsContext for 2d drawing. For some operations i need to edit individual pixels. However, something strange is happening, my pixels are not preserved as they should. I draw red rectangle, half transparent – red is set to 1(255) and transparency to 0.5(128). When i read pixels later on – red is now 128(half its value) and alpha is 128(which is correct). I want to later on find all red pixels with value 255, and change them, but that is not possible, since they are not retaining the set value. Here is my code:
UIGraphicsBeginImageContextWithOptions(CGSizeMake(widthT, heightT), NO, 1);
CGContextRef contextRef = UIGraphicsGetCurrentContext();
//CGContextSaveGState(contextRef);
CGContextSetRGBFillColor(contextRef, 1, 0, 0, 0.5);
CGContextSetRGBStrokeColor(contextRef, 1, 0, 0, 0.5);
CGContextFillRect(contextRef, CGRectMake(0, 0, 400, 400));
UIImage *imageMoonMask = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//NSData *data = (NSData *)CGDataProviderCopyData(CGImageGetDataProvider(image.CGImage));
NSData *data = (NSData *)CGDataProviderCopyData(CGImageGetDataProvider(imageMoonMask.CGImage));
Byte *copyPixels = (Byte *)[data bytes];
pixels = (Byte *) malloc([data length] * sizeof (Byte));
for(int i = 0; i < [data length]; i += 4) {
pixels[i] = copyPixels[i];
pixels[i+1] = copyPixels[i+1];
pixels[i+2] = copyPixels[i+2]; //red color
pixels[i+3] = copyPixels[i+3]; //alpha
NSLog(@"Originalni");
NSLog(@"%u", pixels[i]);
NSLog(@"%u", pixels[i+1]);
NSLog(@"%u", pixels[i+2]);
NSLog(@"%u", pixels[i+3]);
}
The bytes are stored in premultiplied alpha format, to allow more efficient alpha blending. You could avoid premultiplied alpha by creating a custom bitmap context via Core Graphics e.g.
CGBitmapContextCreate and use kCGImageAlphaLast instead of kCGImageAlphaPremultipliedLast…
But it may be easier to recover the original value just by using