Manipulate Java / Android alpha bytes color int

If I have an int in Java that I use as the Android color (for painting on canvas), how do I manipulate only the alpha component of this int? For example, how can I use the operation for this:

int myOpaqueColor = 0xFFFFFF; float factor = 0; int myTransparentColor = operationThatChangesAlphaBytes(myOpaqueColor, factor); //myTransparentColor should now = 0x00FFFFFF; 

Ideally, it would be useful to multiply these first bytes with any factor , rather than just setting the bytes to a static value.

+48
java android bit-manipulation
Mar 10 '13 at 6:37
source share
5 answers

Check out the Color class.

Your code will look something like this.

 int color = 0xFFFFFFFF; int transparent = Color.argb(0, Color.red(color), Color.green(color), Color.blue(color)); 

So the wrapper of this method might look like this:

 public int adjustAlpha(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 name it to set the transparency to, say, 50%:

 int halfTransparentColor = adjustAlpha(0xFFFFFFFF, 0.5f); 

I think that using the provided Color class is a little more self-documenting, just doing the bit manipulation yourself, plus this is already done for you.

+124
Mar 10 '13 at 6:43
source share

Use ColorUtils # setAlphaComponent in android-support-v4.

+34
Mar 02 '16 at 2:01
source share

Alternative is

 int myOpaqueColor = 0xffffffff; byte factor = 20;// 0-255; int color = ( factor << 24 ) | ( myOpaqueColor & 0x00ffffff ); 

Or using float:

 int myOpaqueColor = 0xffffffff; float factor = 0.7f;// 0-1; int color = ( (int) ( factor * 255.0f ) << 24 ) | ( myOpaqueColor & 0x00ffffff); 

You can change any channel by changing the bit value of 24 .

 public final static byte ALPHA_CHANNEL = 24; public final static byte RED_CHANNEL = 16; public final static byte GREEN_CHANNEL = 8; public final static byte BLUE_CHANNEL = 0; // using: byte red = 0xff; byte green = 0xff; byte blue = 0xff; byte alpha = 0xff; int color = ( alpha << ALPHA_CHANNEL ) | ( red << RED_CHANNEL ) | ( green << GREEN_CHANNEL ) | ( blue << BLUE_CHANNEL );// 0xffffffff 
+33
Oct 10 '13 at 4:32
source share

in android-support-v4.

 int alpha = 85; textView.setBackgroundColor(ColorUtils.setAlphaComponent(Color.Red,alpha)); 
+12
Oct 22 '16 at 12:54 on
source share

This doesn't directly answer the question, but it's good to remember that View and Drawable have a setAlpha (float alpha) method that can do what you want. Or you can try view.getBackground (). SetAlpha ().

+1
Sep 14 '15 at 22:46
source share



All Articles