Home > Coding, News > Colored UIImage from grayscale image

Colored UIImage from grayscale image

November 19th, 2012 Leave a comment Go to comments

For a very long time I couldn’t solve one problem that appeared time by time. Until it happened again a few day ago. But this time I decided that to put up with this state of affairs is not more possible and once again began to research. And the problem is the following. Assume you have a the monochrome image (for example, the icon of the stars for the Favorites button), and a skeleton application that implements the usage of skins (customization of the user interface). If one client wants the star to be red and another client wants it to be blue, the designer would have to repaint the image each time. But there must be an easier way to give a tint color using CoreGraphics functions.

My goal was to apply this approach to the component of UIButton, but it is not hard to realize, there is is no difference for other components that worked with UIImage (for example, UIImageView). I’d just like to notice that the way I found after a long search, gave pixelated image output when run on a retina display. This was fixed by replacing the function UIGraphicsBeginImageContext UIGraphicsBeginImageContextWithOptionsTotal. Finally we have the following code::

- (UIImage *) imageByName:(NSString *)name withColor:(UIColor *)color {
    // load the image
    UIImage *img =  = [UIImage imageWithContentsOfFile:name];
    // begin a new image context, to draw our colored image onto
//    UIGraphicsBeginImageContext(img.size);
    UIGraphicsBeginImageContextWithOptions(img.size, NO, [UIScreen mainScreen].scale);
    // get a reference to that context we created
    CGContextRef context = UIGraphicsGetCurrentContext();
    // set the fill color
    [color setFill];
    // translate/flip the graphics context (for transforming from CG* coords to UI* coords
    CGContextTranslateCTM(context, 0, img.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextSetBlendMode(context, kCGBlendModeMultiply);
    CGRect rect = CGRectMake(0, 0, img.size.width, img.size.height);
    CGContextDrawImage(context, rect, img.CGImage);
    // set a mask that matches the shape of the image, then draw (color burn) a colored rectangle
    CGContextClipToMask(context, rect, img.CGImage);
    CGContextAddRect(context, rect);
    // generate a new UIImage from the graphics context we drew onto
    UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();
    //return the color-burned image
    return coloredImg;
Categories: Coding, News Tags: ,
  1. parkour
    May 14th, 2013 at 17:13 | #1

    I have encountered the same problem as you, and you can share with your Demo for me? Thanks very much