Manipulate alpha bytes of Java/Android color int

后端 未结 5 1762
星月不相逢
星月不相逢 2021-01-31 01:14

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 o

5条回答
  •  独厮守ぢ
    2021-01-31 01:50

    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
    

提交回复
热议问题