操作 Java/Android 彩色 int 的 alpha 字节

如果在 Java 中有一个 int 用作 Android 颜色(用于在画布上绘制) ,那么如何操作该 int 的 alpha 组件呢?例如,我如何使用一个操作来做到这一点:

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

理想情况下,最好将这些第一个字节乘以 factor,而不是仅仅将字节设置为静态值。

47369 次浏览

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.

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

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

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