Change int color opacity in java/android Change int color opacity in java/android android android

Change int color opacity in java/android


Wouldn't it be sufficient?

colorDrawerItemSelected = (colorDrawerItemSelected & 0x00FFFFFF) | 0x40000000;

It saves the color value and sets the alpha to 25% of max.

First byte in the color int is responsible for the transparency: 0 - completely transparent, 255 (0xFF) – opaque. In the first part ("&" operation) we set the first byte to 0 and left other bytes untouched. In the second part we set the first byte to 0x40 which is the 25% of 0xFF (255 / 4 ≈ 64).


I use this approach in my app:

private int getTransparentColor(int color){    int alpha = Color.alpha(color);    int red = Color.red(color);    int green = Color.green(color);    int blue = Color.blue(color);    // Set alpha based on your logic, here I'm making it 25% of it's initial value.     alpha *= 0.25;    return Color.argb(alpha, red, green, blue);}

You can also use ColorUtils.alphaComponent(color, alpha) from the support lib.


Use ColorUtils.setAlphaComponent(color, alpha) to set the alpha value to a color easy. The ColorUtils class is in the android support lib.