Reputation: 12215
I'm developping an app that paint on layers. Here's a sample code which show the way I paint.
UIImageView * currentLayer = // getting the right layer...
UIGraphicsBeginImageContext(currentLayer.frame.size);
[currentLayer.image drawInRect:currentLayer.bounds];
// Painting...
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
currentLayer.image = img;
UIGraphicsEndImageContext();
So I have an image (1024x768) which have two kinds of pixels:
- painted ones (same colour for each)
- transparent ones
What is the best way to change the color of the whole layer opaque pixels, knowing that all pixels have the same color?
Do I have to redraw each opaque pixel one by one?
EDIT :
as David Rönnqvist suggested, is tryed by masking a filled image with my layer.
The layer which I want to change color is self.image
:
// Creating image full of color
CGRect imRect = self.bounds;
UIGraphicsBeginImageContext(imRect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, imRect);
UIImage * fill = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// masking the image
CGImageRef maskRef = [self.image CGImage];
CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef), NULL, false);
CGImageRef masked = CGImageCreateWithMask([fill CGImage], mask);
self.image = [UIImage imageWithCGImage:masked];
Almost ! It masks the exact oposite of my layer: only alpha pixels are painted...
Any idea ?
Upvotes: 0
Views: 872
Reputation: 12215
It was very simple, in fact.
UIImage has a method : drawInRect
which only draws opaque pixels.
Here's the code (called from an UIImageView
):
CGRect rect = self.bounds;
UIGraphicsBeginImageContext(rect.size);
[self.image drawInRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetBlendMode(context, kCGBlendModeSourceIn);
CGContextSetFillColorWithColor(context, newColor.CGColor);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Many thanks to iPhone - How do you color an image?
Upvotes: 1