Manipulate alpha bytes of Java/Android color int

二次信任 提交于 2019-12-03 04:27:02

问题


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.


回答1:


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.




回答2:


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




回答3:


in the android-support-v4:

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



回答4:


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



回答5:


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



来源:https://stackoverflow.com/questions/15319635/manipulate-alpha-bytes-of-java-android-color-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!