Make custom image respect tintColor property iOS

Jason Renaldo picture Jason Renaldo · Jan 2, 2014 · Viewed 8.4k times · Source

I have to imagine this has been asked several times, but I must not be wording my question correctly.

I have my own custom image I made in photoshop and it is set as a button's image property. Here it is showing normally:

enter image description here

The background is transparent, but it is 44x44 with the three dots being a 88x88 pixel .png file. So if I do something like this:

self.theButton.tintColor = [UIColor redColor];

the image still shows as white. I am not a designer by trade, so I seem to be missing how to properly save or set up the files to make them respect the tintColor property. In photoshop, I usually save these using "Save for web".

Thanks

Answer

Tyler Cloutier picture Tyler Cloutier · Jan 2, 2014

What you are looking for are stencil images.

From the UIKit User Interface Catalog:

Template Images

In iOS 7, you can choose to treat any of the images in your app as a template—or stencil—image. When you elect to treat an image as a template, the system ignores the image’s color information and creates an image stencil based on the alpha values in the image (parts of the image with an alpha value of less than 1.0 get treated as completely transparent). This stencil can then be recolored using tintColor to match the rest of your user interface.

By default, an image (UIImage) is created with UIImageRenderingModeAutomatic. If you have UIImageRenderingModeAutomatic set on your image, it will be treated as template or original based on its context. Certain UIKit elements—including navigation bars, tab bars, toolbars, segmented controls—automatically treat their foreground images as templates, although their background images are treated as original. Other elements—such as image views and web views—treat their images as originals. If you want your image to always be treated as a template regardless of context, set UIImageRenderingModeAlwaysTemplate; if you want your image to always be treated as original, set UIImageRenderingModeAlwaysOriginal.

To specify the rendering mode of an image, first create a standard image, and then call the imageWithRenderingMode: method on that image.

UIImage *myImage = [UIImage imageNamed:@"myImageFile.png"]; myImage = [myImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];