# AS3: Calculate the perceived brightness of a colour

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:

 1234567891011121314151617181920212223 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 * rgb * 0.241) + (rgb * rgb * 0.691) + (rgb * rgb * 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

Posted toActionScript Flash