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.
setAlpha(51); Here you can set the opacity between 0 (fully transparent) to 255 (completely opaque). The 51 is exactly the 20% you want.
Use imageView. setAlpha(100) .
android.graphics.Color. The Color class provides methods for creating, converting and manipulating colors. Colors have three different representations: Color ints, the most common representation. Color longs.
The Color class defines methods for creating and converting color ints. Colors are represented as packed ints, made up of 4 bytes: alpha, red, green, blue. The values are unpremultiplied, meaning any transparency is stored solely in the alpha component, and not in the color components.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With