4/11/2011

Getting Gradient Colors Between 2 Colors

Here is a function that calculates and returns all the colors between any 2 colors.

AS3 allows for gradient with beginGradientFill, but what if you want to find a color that's in the transition between two colors? The Color class has a useful static function that does just that. import fl.motion.Color; var betweenColor=Color.interpolateColor(color1,color2,ratio); ratio is a number between 0-1. It determines the interpolated color between color1 and color2. Imagine a gradient fill with color1 on one end and color2 on another. A ratio 0.4 returns the color that is 40% away from color1 on that gradient.


Expanding on this little function, we can get as many colors that lie between two colors as we want. This next function takes an array of colors in hexadecimal format. Each color in the array is separated by the number of gradient steps you want between the colors. It should be in the format [color,steps,color,steps,color,...]

FOR EXAMPLE:
To get 10 gradient colors between red(0xFF0000) and blue(0x0000FF), the following array would be passed: var colors:Array=getColorsBetween([0xFF0000,10,0x0000FF]); As a result, colors would be an array of size 12 beginning with red that gradually ends in blue. It can handle multiple colors as long as the array format is proper. Here is an gummy worm made with this function... mesmerizing...


Each circle is following its previous circle via smooth follow.
Each circle's depth is arranged on stage according to its x position on stage. Snippet to do that at the bottom of this page.
Colors are determined with the following function:
import fl.motion.Color; function getColorsBetween(arry:Array):Array{ // Note the length of our array. var len:int=arry.length-1; // Create an array to store all colors. var newArry:Array=new Array(); // For every pair of colors. for (var i:int=0; i<len; i+=2){ // Note the color pair. var hex:uint=arry[i]; var hex2:uint=arry[i+2]; // Add the first color to the array. newArry.push(hex); // Retrieve number of new colors between 1st and 2nd color. var steps:int=arry[i+1]+1; // For each new color. for(var j:int=1; j<steps; j++){ // Determine where the color lies between the 2 end colors. var ratio:Number=j/steps; // get color at step and add to array. newArry.push(Color.interpolateColor(hex,hex2,ratio)); } } // Add the last color to the end of the array. newArry.push(arry[len]); // Return the new array of colors. return newArry; }

2 comments:

  1. Inspiring thank you

    ReplyDelete
  2. Thank you, that was helpfull and straight to the point

    ReplyDelete