Last Updated: February 25, 2016
· tomkr

Creating colored images in iOS

I was recently working on a button with an icon that changes color on highlight. The easiest way to do this seemed to me to just add different color icons to my app, but since Apple changes the colors of your assets with tint color, there had to be a different way.

In the end I came across this gist that does exactly what I wanted to. I modified it a bit to implement it as a category on UIImage. That way I can keep the image around, and get it in a different color when I need it.

The code is pretty much straight from the gist, I added the comments so you can see what is going on.

- (UIImage *)colorImageWithColor:(UIColor *)color
    // Make a rectangle the size of your image
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    // Create a new bitmap context based on the current image's size and scale, that has opacity
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, self.scale);
    // Get a reference to the current context (which you just created)
    CGContextRef c = UIGraphicsGetCurrentContext();
    // Draw your image into the context we created
    [self drawInRect:rect];
    // Set the fill color of the context
    CGContextSetFillColorWithColor(c, [color CGColor]);
    // This sets the blend mode, which is not super helpful. Basically it uses the your fill color with the alpha of the image and vice versa. I'll include a link with more info.
    CGContextSetBlendMode(c, kCGBlendModeSourceAtop);
    // Now you apply the color and blend mode onto your context.
    CGContextFillRect(c, rect);
    // You grab the result of all this drawing from the context.
    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
    // And you return it.
    return result;

Whew, I think this digs into some of the iOS drawing mechanics, but not too deeply to be immediately overwhelmed. Want to read more about this? Here are some links.

1 Response
Add your response


Thanks! Helped me a lot

over 1 year ago ·