How would I tint an image programmatically on iOS?

willc2 picture willc2 · Jul 13, 2009 · Viewed 56.5k times · Source

I would like to tint an image with a color reference. The results should look like the Multiply blending mode in Photoshop, where whites would be replaced with tint:

alt text

I will be changing the color value continuously.

Follow up: I would put the code to do this in my ImageView's drawRect: method, right?

As always, a code snippet would greatly aid in my understanding, as opposed to a link.

Update: Subclassing a UIImageView with the code Ramin suggested.

I put this in viewDidLoad: of my view controller:

[self.lena setImage:[UIImage imageNamed:kImageName]];
[self.lena setOverlayColor:[UIColor blueColor]];
[super viewDidLoad];

I see the image, but it is not being tinted. I also tried loading other images, setting the image in IB, and calling setNeedsDisplay: in my view controller.

Update: drawRect: is not being called.

Final update: I found an old project that had an imageView set up properly so I could test Ramin's code and it works like a charm!

Final, final update:

For those of you just learning about Core Graphics, here is the simplest thing that could possibly work.

In your subclassed UIView:

- (void)drawRect:(CGRect)rect {

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColor(context, CGColorGetComponents([UIColor colorWithRed:0.5 green:0.5 blue:0 alpha:1].CGColor)); // don't make color too saturated

    CGContextFillRect(context, rect); // draw base

    [[UIImage imageNamed:@"someImage.png"] drawInRect: rect blendMode:kCGBlendModeOverlay alpha:1.0]; // draw image
}

Answer

Toland Hon picture Toland Hon · Oct 1, 2013

In iOS7, they've introduced tintColor property on UIImageView and renderingMode on UIImage. To tint an UIImage on iOS7, all you have to do is:

UIImageView* imageView = …
UIImage* originalImage = …
UIImage* imageForRendering = [originalImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
imageView.image = imageForRendering;
imageView.tintColor = [UIColor redColor]; // or any color you want to tint it with