How to color-fill a black and transparent image in iOS?

Qiming picture Qiming · Aug 18, 2012 · Viewed 10.1k times · Source

For example, in the iOS toolbar, you drag in your own .png which is opaque black and transparent, and it automatically adds the iOS blue gloss.

However, I'd like to know how to do this yourself, but just solid colors will do.

For example, if you had this image: Example

What would you do to make that entire solid, pink, or blue, or grey? I want to cut down on the number of versions of .png's I save in my app by colorizing them with code.

Thank you!

Answer

David H picture David H · Aug 18, 2012

This should do it for you:

- (UIImage *)colorImage:(UIImage *)origImage withColor:(UIColor *)color
{
    UIGraphicsBeginImageContextWithOptions(origImage.size, YES, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, (CGRect){ {0,0}, origImage.size} );

    CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, origImage.size.height);
    CGContextConcatCTM(context, flipVertical);
    CGContextDrawImage(context, (CGRect){ pt, origImage.size }, [origImage CGImage]);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}