93

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.

jnpdx
  • 45,847
  • 6
  • 64
  • 94

5 Answers5

195

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.

Patrick
  • 33,984
  • 10
  • 106
  • 126
majormajors
  • 2,351
  • 1
  • 14
  • 7
89

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

Chris Stillwell
  • 10,266
  • 10
  • 67
  • 77
chenupt
  • 1,781
  • 1
  • 14
  • 13
76

in the android-support-v4:

int alpha = 85; //between 0-255
@ColorInt
int alphaColor = ColorUtils.setAlphaComponent(Color.Red, alpha);
Patrick
  • 33,984
  • 10
  • 106
  • 126
Masoud Siahkali
  • 5,100
  • 1
  • 29
  • 18
40

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
Ratata Tata
  • 2,781
  • 1
  • 34
  • 49
1

This isn't directly answering the question but it's good to remember that View and Drawable have a setAlpha(float alpha) method which might do what you want. Or you might want to try view.getBackground().setAlpha().

miguel
  • 16,205
  • 4
  • 53
  • 64