During development, there comes a time where you need the same icon but in a slightly different color shade. For example, when implementing dark and light modes, you want the icons to be visible and stand out against the theme selected.
One simple way of doing this is by importing an entirely different image. However, this implementation has a couple of drawbacks as outlined below.
- Another set of dark mode images increases the overall app size.
- For each image that needs to be switched, explicit styles or converters need to be implemented which can be tedious and a nightmare to maintain.
Another way of going around this problem is through effects. Effects simplify the customization of controls and are typically used for small styling changes such as color updates.
Implementing Tint Effect
We first add a new folder called effects in the Netstandard project and created a TintImageEffect class. Next, we create a bindable property and using the property changed method we handle any color changes as shown below
For each Xamarin control, we will need a different implementation to retrieve the image from the control. ImageView are simple as its main component is an image. Other controls such as buttons or search view will need a little more digging to get the image component from the parent view as shown below. The concept should be the same for other controls that might need the tint effect implementation.
The following code shows the TintEffect implementation for the iOS project
The following code shows the TintEffect implementation for the Android project
Consuming the effect
To use the effect, you can simply add it a property in xaml as shown below
Alternatively, you can create an explicit or implicit style in you App.xaml class.