Manipulate alpha bytes of Java/Android color int

jn_pdx picture jn_pdx · Mar 10, 2013 · Viewed 38.4k times · Source

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.

Answer

majormajors picture majormajors · Mar 10, 2013

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.