I would love to know how to color an image (make a white .png red, for example). I have seen various suggestions but never any confirmation that this is actually possible. I have tried this:
-(UIImage *)colorizeImage:(UIImage *)baseImage color:(UIColor *)theColor {
UIGraphicsBeginImageContext(baseImage.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect area = CGRectMake(0, 0, baseImage.size.width, baseImage.size.height);
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -area.size.height);
CGContextSaveGState(ctx);
CGContextClipToMask(ctx, area, baseImage.CGImage);
[theColor set];
CGContextFillRect(ctx, area);
CGContextRestoreGState(ctx);
CGContextSetBlendMode(ctx, kCGBlendModeNormal);
CGContextDrawImage(ctx, area, baseImage.CGImage);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
myImageView.image = [self colorizeImage:[UIImage imageNamed:@"whiteImage.png"] color:[UIColor redColor]];
But it doesn't work - the image is still white on the screen.
Short, sweet and better :)
- (UIImage *)colorizeImage:(UIImage *)image withColor:(UIColor *)color
Define
UIColorFromRGB
to use hex color codes then just callcolorizeImage:withColor
@geek kid, let me know if this helps u dude...
//replace "context" with
UIGraphicsGetCurrentContext()
or if u have an instance of the current context.Hope that helps.
If you set the backgroundColor of an UIImageView to [UIColor redColor], the parts of the original PNG that were transparent will become red. Alternatively, you could try adding a semi-transparent UIView with background color red as subview of the imageview. This will add a red haze to the view displaying the image.
You're drawing the color first, and then drawing the image on top of it. Unless the image is partially transparent, it's going to completely overdraw the background color. I recommend trying to draw the original image first, and then drawing red over it using
kCGBlendModeHue
.I'm not certain why you're flipping and translating your context. Is your picture upside down?
Okay, how's this?
In your asset creation phase (NOT dynamically while the application is running), invert the color scheme of your images. Part that is now white -> transparent. Part that is now transparent -> whatever the background of the page is.
Under each image, place a blank white view of the same size. When you wish to turn the image to red, change the color of that blank white view to red.
Is that doable?
Make this a UIImage category. It also takes into account the scale factor with iOS 4.
UPDATE - Swift version: