DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 3.2 Specifying RGB Values

3.2.1 Problem

You want to create an RGB value to use with setRGB( ) based on the red, green, and blue part values.

3.2.2 Solution

Use the bitshift left and bitwise OR operators.

3.2.3 Discussion

The easiest way to combine individual red, green, and blue components into a single RGB value is to use bitwise operations. Simply shift the red value left by 16 bits and the green value left by 8 bits, then combine them with the blue value using the bitwise OR operator, as follows:

red   = 100;
green = 100;
blue  = 100;
rgb = (red << 16) | (green << 8) | (blue);

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

// Set the RGB color.
my_color.setRGB(rgb);

The bitshift left operator (<<) effectively multiplies a number by two for each bit position that the number is shifted (this is similar to how shifting a decimal number one decimal place to the left effectively multiplies it by 10). In this context, the bitwise OR operator (|) essentially concatenates the shifted numbers together. Therefore, assuming that red, green, and blue are each in the range of 0 to 255, the following:

rgb = (red << 16) | (green << 8) | (blue);

is equivalent to:

rgb = (red * Math.pow(2,16)) + (green * Math.pow(2,8)) + blue;

or:

rgb = (red * 65536) + (green * 256) + blue;

In practice, it is often easier to use Color.setTransform( )—in which the red, green, and blue components are specified as separate properties of a transform object—to alter the targeted clip's color. Furthermore, setTransform( ) allows you to set the alpha value for a color, which setRGB( ) does not.

3.2.4 See Also

Recipe 3.7

    [ Team LiB ] Previous Section Next Section