Manipulate alpha bytes of Java/Android color int

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.


in the android-support-v4:

int alpha = 85; //between 0-255
@ColorInt
int alphaColor = ColorUtils.setAlphaComponent(Color.Red, alpha);

An 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 bitwise value 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