Search code examples
javaandroidinttransparencyalpha

Change int color opacity in java/android


I am trying to change the opacity of a color that I get of my theme with the next code:

TypedValue typedValueDrawerSelected = new TypedValue();
getTheme().resolveAttribute(R.attr.colorPrimary, typedValueDrawerSelected, true);
int colorDrawerItemSelected = typedValueDrawerSelected.data;

I want that the colorDrawerItemSelected keeps the same color, buth its alpha should be 25%.

I found some solutions getting the rgb color from the imageView, but I havent imageView.

Thank you for your time.


Solution

  • 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).