Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulate alpha bytes of Java/Android color int

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.

like image 844
jnpdx Avatar asked Mar 10 '13 06:03

jnpdx


People also ask

How to use color in Android?

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

How do I change the color of the opacity on my Android?

setAlpha(51); Here you can set the opacity between 0 (fully transparent) to 255 (completely opaque). The 51 is exactly the 20% you want.

What is color in Android?

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.


2 Answers

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.

like image 94
majormajors Avatar answered Oct 14 '22 22:10

majormajors


Use ColorUtils#setAlphaComponent in the android-support-v4.

like image 43
chenupt Avatar answered Oct 14 '22 22:10

chenupt