0

I am currently working on a problem where the background of some UI component has to be: the main color of the screen plus a 30% opacity.

The main color is retrieved from a backend service and comes in the form of: #224466.

Now, I would like to apply 30% opacity to whatever color I receive. The solution I came up with, involves the string parsing, and it's working, but I am not happy with it:

I am doing it like this:

if(mainColor.startsWith("#") && mainColor.length == 7){
   return "#4D" + mainColor.substring(1) // 4D = 30% alpha
}

Do you know if there's perhaps a better way, maybe involving the Color class, of solving the above task?

ashchk
  • 161
  • 13
VCODE
  • 535
  • 5
  • 19

1 Answers1

0

Use Color and ColorUtils

//pass "#224466" dynamically 
private fun getRequiredColor(mainColor: String): Int {
    val color = Color.parseColor(mainColor)
    val colorWithAlpha30 = ColorUtils.setAlphaComponent(color, 0X4D) //30% opacity constant or else you can pass dynamically 
    return colorWithAlpha30
}
TRK P
  • 366
  • 2
  • 9