Saturday, September 19, 2009

Imitate the Flash CS4 Color Palette in Actionscript 3








Open your .fla file and hit Ctrl+J to bring up the Document Properties window. Change the height and width to 400 and 240 pixels respectively and the Background color to 0x000000(Black)
Select the first frame and Hit F9 to bring up the Actions window. Copy and Paste the following code

/*size of each small square representing a color*/
var squareSize=13;

/*number of small squares in each side of a color set*/
var paletteSize = 6;

/*parent sprite container*/
var palette:Sprite = new Sprite();
palette.x = 10;
palette.y = 45
addChild(palette);

/*the square whose color is to be changed*/
var colorSampler:Sprite = new Sprite();
colorSampler.graphics.beginFill(0xFFFFFF);
colorSampler.graphics.drawRect(280,80,100,100);
colorSampler.graphics.endFill();
addChild(colorSampler);

/*create the palette*/
for(var k=0;k<paletteSize;k++)
{
for(var i=0;i
<paletteSize;i++)
{
for(var j=0;j
<paletteSize;j++)
{
var square:Sprite = new Sprite();
square.graphics.beginFill(0xFFFFFF);
square.graphics.drawRect(0,0,squareSize,squareSize);
square.graphics.endFill();
square.x = (squareSize+1)*paletteSize*(k%3)+i*(squareSize+1);
square.y = (squareSize+1)*paletteSize*(Math.floor(k/3))+j*(squareSize+1);
/*add a gradual color to each small square.
By this distribution, the palette will have 6
color sets each made up of 6x6 small
squares. In all of these color sets there will
be an increasing amount of the GREEN mask along
the horizontal direction, and the BLUE mask along
the vertical direction. The red mask is distributed
over these 6 sets.
*/

var color:ColorTransform = new ColorTransform();
color.greenMultiplier = i/(paletteSize-1);
color.blueMultiplier = j/(paletteSize-1);
color.redMultiplier = k/(paletteSize-1);
square.transform.colorTransform=color;

palette.addChild(square);

/*listen for a click on the small square*/
square.addEventListener(MouseEvent.CLICK,clickHandler);
}
}
}


/*change the color of the square*/
function clickHandler(e:MouseEvent) {

/*the color masks are actually found by processing
the position of the clicked small square*/

var X=e.currentTarget.x;
var Y=e.currentTarget.y;
X=X/(squareSize+1);
Y=Y/(squareSize+1);
var Z=Math.floor(X/paletteSize)+Math.floor(Y/paletteSize)*3;
X=X-Math.floor(X/paletteSize)*paletteSize;
Y=Y-Math.floor(Y/paletteSize)*paletteSize;

/*apply the new color*/
var color:ColorTransform = new ColorTransform();
color.greenMultiplier =X/(paletteSize-1);
color.blueMultiplier =Y/(paletteSize-1);
color.redMultiplier = Z/(paletteSize-1);
colorSampler.transform.colorTransform=color;
}

Thats it!! Hit Ctrl+Enter to Test your movie.
Change the code to make the palette more detailed and sensitive.
Just like the color palette in Flash CS4, you can add a slider that darkens any given color. This can be achieved by gradually decreasing all the color masks simutaneously.

No comments:

Post a Comment