问题
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.
回答1:
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).
回答2:
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.
回答3:
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);
回答4:
Use ColorUtils.setAlphaComponent(color, alpha) to set the alpha value to a color easy. The ColorUtils class is in the android support lib.
来源:https://stackoverflow.com/questions/28483497/change-int-color-opacity-in-java-android