Tuesday, August 2, 2011

Color in Hex and separated to RGB channels

I don't know why conversion between hex code of color and separating it into RGB channels is not built in AS3.0 classes. It's quite easy operation. Here are methods for both directions:

function hex2RGB ( hex:Number ):Object 
{
var rgb:Object = new Object();
rgb.r = (hex & 0xff0000) >> 16;
rgb.g = (hex & 0x00ff00) >> 8;
rgb.b = hex & 0x0000ff;
trace(rgb.r, rgb.g, rgb.b);
return rgb;
}


Usage:
hex2RGB(0xE60E3F); // 230, 14, 63

It's more functional to operate on one object so the function returns it. For testing purpose there is trace that prints values of channels

function RGB2hex (r:uint, g:uint, b:uint):Number
{
return ((r << 16) + (g << 8) + b);
}

Usage:
trace(RGB2hex(230, 14, 63).toString(16));
For displaying purpose the radix has been changed to 16 (hex)

No comments:

Post a Comment