Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tint the background images of an UIButton programmatically and dynamically?

I am working on an app - or rather on some re-usable "framework" which I am happy to share once it works. Within this app the user should be able to choose from a list of color themes. Therefore the app must be able to tint its UI elements in some rather dynamic way.

For Buttons all the tinting does not work. Properly tinted background images must be supplied here. But preparing one set of background images for each them is just second best. It is not dynamic and flexible enough.

In the end a solution may come down to providing one monochrome (grey) gradiented image for the selected and normal state and tint that image programmatically using CoreGraphics or OpenGL. But frankly, I do not know where to start there. How should the gradient look like and how would I then programmatically tint that in any given color?

Pretty much applies to UISegmentedControls, just a bit more complicated. :) Any generic solution that covers UISegementedControls too is highliy appreciated.

like image 679
Hermann Klecker Avatar asked Jan 24 '13 22:01

Hermann Klecker


1 Answers

In iOS7 you can use the method imagedWithRenderingMode: in conjunction with the method setTintColor:

But, be sure to use UIImageRenderingModeAlwaysTemplate as it replaces all non-transparent colors on a UIImage with the tint color. The default is UIImageRenderingModeAutomatic.

UIImageRenderingModeAlwaysTemplate

Always draw the image as a template image, ignoring its color information.

Objective-C:

UIImage * image = [myButton.currentImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[myButton setImage:image forState:UIControlStateNormal];

Swift:

let image = myButton.currentImage?.withRenderingMode(.alwaysTemplate)
myButton.setImage(image, for: .normal)
like image 126
Jonathan Avatar answered Sep 30 '22 08:09

Jonathan