This short post is mainly just a reference for myself but could also come in handy in your projects. I wanted to set text to either white or black depending on the brightness of the colour it was sitting on. I came across this post which provided a formula and some C# code so I was easily able to convert it to AS3. Since red,green and blue are not equally as bright – eg. blue is darker than green – its not as simple as taking an average of all the channels. So the following formula uses some factors to weight the channels in relation to how bright they really appear.

brightness = sqrt( 0.241 R2  + 0.691 G2  + 0.068 B2  )

Here is a demo and below that, the snippet of code:

var myColour:uint = 0xFFCC33;

// get brightness value between 0 (black) and 1 (white)
brightness = determineBrightness( 0xFFCC33 );

function determineBrightness(colour:uint):Number
{
  var rgb:Array = HexToRGB(colour);

  return Math.sqrt((rgb[0] * rgb[0] * 0.241) + (rgb[1] * rgb[1] * 0.691) + (rgb[2] * rgb[2] * 0.068) ) / 255;
}

function HexToRGB(hex:uint):Array
{
  var rgb:Array = [];

  var r:uint = hex >> 16 & 0xFF;
  var g:uint = hex >> 8 & 0xFF;
  var b:uint = hex & 0xFF;

  rgb.push(r, g, b);
  return rgb;
}

Featured Image: Enrapture by synthetic innocence on ColorLovers