Usage of images with “Template Image” render mode in iOS

The most common usages of template images are NavigationBar items, TabBar items, UIButton’s image and so on. But you can also use it for your own goals and change image color in runtime.

For example you want to add pacman-like ghosts that will be lurking around your UI. These ghosts could have different colors, like: pink, blue, purple and green. Normally you can just create assets for each ghost’s color and import it into your project:

Different images for different ghosts colors

In code you’ll need to implement logic with definition of what image to use for each ghost on your screen. Pretty simple, isn’t it?

Now you want to improve your idea and make more different ghosts colors, or even force them to change their colors while moving. Here when the problem appear.

Solution with different images for different kinds of same image isn’t a future-proof thing. It requires changes in xcassets folder and in code each time you need to extend it. Also it increases application’s size and loading time.

That’s when images render mode comes to help us.

Changing image render mode to “Template Image”

You can simply change image’s render mode to Template Image right in Xcode:

Set render mode to "Template Image" in Xcode

You can also do this in code:

UIImage(named: "PacmanGhost")?
    .imageWithRenderingMode(
        UIImageRenderingMode.AlwaysTemplate
    )

Usage of template images

Now you can use this template image in many places:

  • in UIBarButtonItem with tintColor property
  • in UIButton by setting image property and modifying tintColor property
  • in UIImageView along with tintColor property

Let’s update our ViewController to create several ghost with desired colors:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.placeGhost(UIColor.ghostPinkColor(), position: CGPointMake(58, 40));
        self.placeGhost(UIColor.ghostGreenColor(), position: CGPointMake(120, 80));
        self.placeGhost(UIColor.ghostBlueColor(), position: CGPointMake(78, 130));
    }

    func placeGhost(color: UIColor, position: CGPoint) {
        let imageView: UIImageView = UIImageView(frame: CGRectMake(position.x, position.y, 0, 0))
        imageView.image = UIImage(named: "PacmanGhost")
        imageView.tintColor = color
        imageView.sizeToFit()
        self.view.addSubview(imageView)
    }

}

As the result we’ll see several ghosts on our screen:

Template images in action

Updated:

Leave a Comment