Change int opacity of color in java / android

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

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

I want colorDrawerItemSelected keep the same color, but its alpha value should be 25%.

I found some solutions getting rgb color from imageView, but I don't have an image.

Thank you for your time.

+7
java android int transparency alpha
source share
4 answers

Wouldn't it be enough?

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

Preserves the color value and sets alpha to 25% of the maximum.

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

+17
source share
 int[] attrs = new int[] { android.R.attr.colorPrimary }; TypedArray a = obtainStyledAttributes(attrs); int colorPrimary = a.getColor(0, 0); a.recycle(); 

Now you can change the opacity of colorPrimary by updating the highest 8 bits:

 //set new color int newColor = (colorPrimary & 0x00FFFFFF) | (0x40 << 24); 
+6
source share

I use this approach in my application:

 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 initial value. alpha *= 0.25; return Color.argb(alpha, red, green, blue); } 

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

+4
source share

Use ColorUtils.setAlphaComponent (color, alpha) to set the alpha value for the color. The ColorUtils class is in the android support library.

0
source share

All Articles