Sitemap

Darken or Lighten a color on Android programmatically!

3 min readOct 31, 2021
Press enter or click to view image in full size

Hey πŸ‘‹

In this blog, I will quickly share a way to programatically compute a darker or lighter version of a color on Android using different color models and some simple maths.

There can be many use cases for this, if we have one main color value we can use it as the background for a view and add a darker color stroke or we can compute another shade and create a gradient with the main color to use that as the background.

It becomes even sweeter if the main color is coming from a remote source like a network call, the backend only needs to store and send the main color, the darker/lighter shade can be computed on run time 🐴

Press enter or click to view image in full size
Some usages for having a different color shade

Normally when we have a color instance in Android, internally the color information is stored in ARGB model. Now, we can not update the brightness of the color in this model, alpha changes the opacity and updating any of the other values will completely mess up the color itself. But, there is another color model called the HSV model which stores the Hue, Saturation and Value. The Value is also called the brightness or the lightness. To our luck, android allows us to convert color to and back from the HSV color model πŸ˜„.

The Value parameter is a Float which can take values from 0 to 1. 0 would make it black and 1 would bring out the brightest shade.

Press enter or click to view image in full size
Effect of changing β€œValue” on the color shade

So if we want to make the color 30% darker, we need to:

  1. Convert color instance to HSV color model array
  2. Reduce the third parameter i.e. Value by 30%
  3. Convert back to standard color instance
Function in kotlin to darken the color by 30%

And that’s it, we have a 30% darker color shade. Similarly we can increase the Value to a maximum of 1, to lighten the color.

That was a useful trick I use to change the color shade. If you do try this, also experiment with the Hue and the Saturation, you are in for some cool results πŸ‘». Hope you get to use this in one of your projects and if you have similar tips, make sure you post them in the comments!

Until the next one, Ciao!

Press enter or click to view image in full size