O'Reilly logo

Actionscript Cookbook by Joey Lott

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.3. Decoding an RGB Value

Problem

You want to extract the red, green, and blue components from an RGB value returned by Color.getRGB( ).

Solution

Use the bitshift right and bitwise AND operators.

Discussion

You can extract the red, green, and blue components from the single RGB value returned by Color.getRGB( ) using the bitshift right (>>) and bitwise AND (&) operators. You can extract one or more of the colors individually as follows:

// Create the Color object.
my_color = new Color(myMovieClip);

// Get the current RGB color.
rgb = my_color.getRGB(  );

// rgb contains an RGB color value in decimal form, such as 14501017 (rosy pink), 
// which is stored internally as its hex equivalent, such as 0xDD4499.
red   = (rgb >> 16);
green = (rgb >> 8) & 0xFF;
blue  =  rgb & 0xFF;

Although displayed as a decimal number, remember that each color is stored internally in its hexadecimal form: 0x RRGGBB. For example, the color value 14501017 (which is rosy pink) is stored internally as 0xDD4499. In this format, it is easy to see that the red component is DD in hex (221 in decimal), the green component is 44 in hex (68 in decimal), and the blue component is 99 in hex (153 in decimal).

The preceding transformation effectively separates a 24-bit value into its three 8-bit components (the leftmost eight bits represent red, the middle eight bits represent green, and the rightmost eight bits represent blue). The bitshift right operator is used to shift the eight bits of interest to the rightmost position. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required