Flash ActionScript brightenColor Function

0 actionscript,flash,work  |   October 8, 2006  |     483

I’ve been working hard on several projects lately; and have decided to post on here some of the useful functions i’ve developped. Starting with the simplest ones and eventually going into sharing full-blown components.

Today I wish to share a little function that either brightens or darkens a color value, such as 0x445566. Here is the code:

[code lang=”actionscript”]

public static function brightenColor(color:Number, perc:Number):Number {
var factor:Number;

// get the blue offset
var blueOffset:Number = color % 256;

// get the green offset
var greenOffset:Number = ( color >> 8 ) % 256;

// get the red offset
var redOffset:Number = ( color >> 16 ) % 256;

// if percentage is greater than 50, we are making the color brighter
if(perc > 50 && perc <= 100) { // calculate the factor by which we will make the color brighter factor = ( ( perc-50 ) / 50 ); // apply this factor to all offsets redOffset += ( 255 - redOffset ) * factor; blueOffset += ( 255 - blueOffset ) * factor; greenOffset += ( 255 - greenOffset ) * factor; } // else if the percentage is less than 50, we are making the color darker else if( perc < 50 & perc >= 0 )
{
// calculate the factor by which we will make the color darker
factor = ( ( 50 – perc ) / 50 );

// apply the factor to all offsets
redOffset -= redOffset * factor;
blueOffset -= blueOffset * factor;
greenOffset -= greenOffset * factor;
}

// put all offsets back together to form the color value of 0xRRGGBB
return (redOffset<<16|greenOffset<<8|blueOffset); } [/code] Basically, this function decomposes the color value into it's individual components, that is the red, green and blue components. It then applies a factor to this component. If the 'perc' parameter is above 50, it will brighten the color, if the parameter is below 50, it will darken it. The minimum value should be 0, and maximum should be 100. Enjoy!

Comments

Leave a Reply