Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Color Tint UIButton Image

I noticed that when I place a white or black UIImage into a UISegmentedControl it automatically color masks it to match the tint of the segmented control. I thought this was really cool, and was wondering if I could do this elsewhere as well. For example, I have a bunch of buttons that have a uniform shape but varied colors. Instead of making a PNG for each button, could I somehow use this color masking to use the same image for all of them but then set a tint color or something to change their actual color?

like image 452
Logan Shire Avatar asked Nov 07 '13 06:11

Logan Shire


People also ask

What is tint color in IOS?

A color used to tint template images in the view hierarchy.

How do I change the color of an Imagematically in Swift?

The absolute simplest way to change colors of images (or icons in this case) is to use the SF Symbols where applicaple. This is a set of symbols Apple provides that can easily be used in your own app.


2 Answers

As of iOS 7, there is a new method on UIImage to specify the rendering mode. Using the rendering mode UIImageRenderingModeAlwaysTemplate will allow the image color to be controlled by the button's tint color.

Objective-C

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; UIImage *image = [[UIImage imageNamed:@"image_name"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; [button setImage:image forState:UIControlStateNormal];  button.tintColor = [UIColor redColor]; 

Swift

let button = UIButton(type: .custom) let image = UIImage(named: "image_name")?.withRenderingMode(.alwaysTemplate) button.setImage(image, for: .normal) button.tintColor = UIColor.red 
like image 192
Ric Santos Avatar answered Nov 22 '22 10:11

Ric Santos


As Ric already mentioned in his post you can set the render mode in code, you can also do this directly in the image catalog, see attached image below. Just set the Render As to Template Image

enter image description here

Caveat I have had problems with iOS 7 and this approach. So if you use iOS 7 as well you might want to do it in code as well to be sure, as described here.

like image 38
hashier Avatar answered Nov 22 '22 11:11

hashier