Suppose i have background color set as #AF000000(AARRGGBB) in android. I want value of alpha channel(AA) in decimal (0-255) which is going to be 175.
How to accomplish that programatically?
Here is a pure Java solution that doesn't use the Android-specific getAlpha()
method.
Do you have this value stored in a String
or an int
? If you have it in a String
, first get rid of the #
character then convert it to an int
:
String hexString = "#05000000";
int color = Integer.parseInt(hexString.replaceAll("#", ""), 16);
Then we need to make some bit manipulation. This hex color representation means (in ARGB mode) you have the values #AARRGGBB. That is 2 bytes for each channel, including the alpha one. To get just the alpha channel (the AA
part of the hex value), we need to "push it 6 bytes to the right" (Java is a Big Endian languange) so we can end up with something like #000000AA
. Since each byte is comprised of 8 bits, we have to "push" the alpha values 6 * 8 = 24
bits "to the right":
int alpha = color >> 24;
This process is called Bit Shifting. All the rightmost RGB values are discarded and we then have the alpha value stored in an int
with a decimal value between 0 and 255.
EDIT: If you already have the alpha value as returned from getAlpha(), you can always multiply it by 255 and floor it:
int alpha = Math.floor(myView.getAlpha() * 255);