If I have an int in Java that I'm using as an Android color (for drawing on a Canvas), how do I manipulate just the alpha component of that int? For example, how can I use an operation to do this:
int myOpaqueColor = 0xFFFFFF; float factor = 0; int myTransparentColor = operationThatChangesAlphaBytes(myOpaqueColor, factor); //myTransparentColor should now = 0x00FFFFFF;
Ideally, it would be nice to multiply those first bytes by whatever factor
is, rather than just set the bytes to a static value.
Named Color Resources in Android (Note: To add a new resource first select the app in the Project explorer file. Then use the File or context menu, usually right-click, then the New option and select Android resource file. A color resource does not need to be stored in colors. xml, other file names can be used.)
setAlpha(51); Here you can set the opacity between 0 (fully transparent) to 255 (completely opaque). The 51 is exactly the 20% you want.
The hexadecimal color code #a4c639 is a shade of yellow-green. In the RGB color model #a4c639 is comprised of 64.31% red, 77.65% green and 22.35% blue. In the HSL color space #a4c639 has a hue of 74° (degrees), 55% saturation and 50% lightness.
Check out the Color class.
Your code would look a bit something like this.
int color = 0xFFFFFFFF; int transparent = Color.argb(0, Color.red(color), Color.green(color), Color.blue(color));
So wrapping it in a method might look like:
@ColorInt public static int adjustAlpha(@ColorInt int color, float factor) { int alpha = Math.round(Color.alpha(color) * factor); int red = Color.red(color); int green = Color.green(color); int blue = Color.blue(color); return Color.argb(alpha, red, green, blue); }
And then call it to set the transparency to, let's say, 50%:
int halfTransparentColor = adjustAlpha(0xFFFFFFFF, 0.5f);
I think using the provided Color class is a little bit more self-documenting that just doing the bit manipulation yourself, plus it's already done for you.
Use ColorUtils#setAlphaComponent in the android-support-v4.
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