Follow treslines by email clicking Here!

Tuesday, April 1, 2014

How to extract ARGB components from color int value

Hi there!

Today i'm gonna show how to extract the color's component Alpha, Red, Green and Blue from an integer value that presents a specific color. The code is very simple and self-explanatory.

/**
     * Returns the color components as alpha, red, green and blue parts in an array.
     * 

     * argb[0] = alpha value
     * argb[1] = red value
     * argb[2] = green value
     * argb[3] = blue value
     * 
* @param color the color value * @return the array containing the color components */ public static int[] getARGB(int color) { /** * Shift all pixels 24 bits to the right. * Do a logical and with 0x000000FF * i.e. 0000 0000 0000 0000 0000 0000 1111 1111 * You will get the alpha value for the color */ int alpha = (color >> 24) & 0x000000FF; /** * Shift all pixels 16 bits to the right. * Do a logical and with 0x000000FF * i.e. 0000 0000 0000 0000 0000 0000 1111 1111 * You will get the red value for the color */ int red = (color >> 16) & 0x000000FF; /** * Shift all pixels 8 bits to the right. * Do a logical and with 0x000000FF * i.e. 0000 0000 0000 0000 0000 0000 1111 1111 * You will get the green value for the color */ int green = (color >>8 ) & 0x000000FF; /** * Dont do any shift. * Do a logical and with 0x000000FF * i.e. 0000 0000 0000 0000 0000 0000 1111 1111 * You will get the blue value for the color */ int blue = (color) & 0x000000FF; return new int[]{alpha,red,green,blue}; } public static int manipulateAlpha(int color, int newAlpha) { final int[] argb = getARGB(color); return Color.argb(random.nextInt(argb[0]), argb[1], argb[2], argb[3]); }

No comments:

Post a Comment