RevenueCat makes it easy to implement, manage, and grow your app business.
Explore the docs
There are several ways to change a color of an image in iOS. We usually need to change the color of an icon image to fit a theme or part of our app.
Here is an example where images are tinted to match the appearance of an app.
An image painted in blue, yellow, and white to match apps design.
There are several ways to change a color of an image in iOS. We will learn two of them in this article.
Image with template rendering mode and tint color
.
Tinted UIImage directly
.
Image with template rendering mode and tint color
renderingMode
.
Set rendering mode to
.alwaysTemplate
tell the system that you want to use it as an image mask which you can apply any color you want.
Set image rendering mode to always template
What is image rendering mode in iOS
. I recommend you read it if you aren't aware of an image rendering mode.
To apply a color to a template image, you set a property called
tintColor
on a view that uses the image. Since
tintColor
is a UIView property, most views that you can set an image support this out of the box. Even a view that is not a subclass of an UIView also supports tint color, e.g., UIBarButtonItem.
Change color by setting tintColor property
Tinted UIImage directly
first method
since you can't set tint color for each state of a button. We have to change the color of an image and set it for each state.
If your app supports a minimum iOS version of 13, you're in luck. You can change the color of an image with just one line of code.
iOS 13+
withTintColor(_:renderingMode:)
withTintColor(_:)
The following code will returns a new version of the image with a pink color that uses
.alwaysOriginal
rendering mode.
let image = UIImage(named: "Swift")?.withTintColor(.systemPink, renderingMode: .alwaysOriginal)
Here is how we set an image with different colors for a normal and a highlighted state of a button.
let image = UIImage(named: "Swift")?.withTintColor(.systemPink, renderingMode: .alwaysOriginal)
let highlightedImage = UIImage(named: "Swift")?.withTintColor(.systemIndigo, renderingMode: .alwaysOriginal)
let button = UIButton(type: .custom)
button.setImage(image, for: .normal)
button.setImage(highlightedImage, for: .highlighted)
1
Create a new image with a pink color. We will use this image in a button's normal state.
2
Create another image with indigo color. We will use this image in a highlighted state.
3
,
4
Set each image to each state.
Pre iOS 13
Twitter
and ask your questions related to this post. Thanks for reading and see you next time.
If you enjoy my writing, please check out my Patreon
https://www.patreon.com/sarunw
and become my supporter. Sharing the article is also greatly appreciated.