in iOS

Color a UIImage

Sometimes you need to color a UIImage for a UIButton or any other control. Instead of creating two different image resources to accomplish this, use iOS 7 new function:  imageWithRenderingMode

With this cute gem, combined with tintColor, any black-&-white PNG can be coloured into any other colour.

Here’s a quick example on how to use it:

    // init the image using imageWithRenderingMode set to AlwaysTemplate
    UIImage *image = [[UIImage imageNamed:@"checkmark"]
                      imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
 
    // put UIImage in a UIImageView and adjust color with tintColor
    UIImageView *imageView = [[UIImageView alloc]initWithImage:image];
    imageView.tintColor = [UIColor redColor];

And here’s the @”checkmark” image asset:

checkmark@2x

 

Here’s a quick viewcontroller example with result underneath, cheers!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//
//
//  ViewController.m
//  TestUIImage
//
//  Created by Mike on 2014-05-20.
//  Copyright (c) 2014 Mike. All rights reserved.
//
 
#import "ViewController.h"
 
@interface ViewController ()
 
@end
 
@implementation ViewController
 
- (void)viewDidLoad
{
    [super viewDidLoad];
 
    self.view.backgroundColor = [UIColor colorWithWhite:0.7 alpha:1.0f];
    self.view.layer.borderWidth = 1.0f;
    self.view.layer.borderColor = [UIColor darkGrayColor].CGColor;
 
    // init the image using imageWithRenderingMode set to AlwaysTemplate
    UIImage *image = [[UIImage imageNamed:@"checkmark"]
                      imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
 
    // put UIImage in a UIImageView and adjust color with tintColor
    UIImageView *imageView = [[UIImageView alloc]initWithImage:image];
    imageView.tintColor = [UIColor redColor];
 
    CGRect frame = {{(self.view.bounds.size.width-image.size.width)/2,
                    (self.view.bounds.size.height-image.size.height)/2},
                    {image.size.width,image.size.height}};
 
    imageView.frame = frame;
    [self.view addSubview:imageView];
 
    imageView = [[UIImageView alloc]initWithImage:image];
    imageView.tintColor = [UIColor greenColor];
 
    frame = CGRectOffset(frame, 0, image.size.height*1.1);
    imageView.frame = frame;
    [self.view addSubview:imageView];
 
}
 
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
 
@end

 

iOS Simulator Screen shot