Friday, August 13, 2010

How to create a color picker using Actionscript 3

Today we will learn how to make a color picker for our flash application.

Here's how our final product will look like:


First of all we need to get a color spectrum picture (you can draw it yourself if you wish), I used this one:



Put it on the stage, convert it to a MovieClip. Make sure that the registration point is in top left corner! Gvie the MC an instance of "colorPicker". Create two dynamic textfields - textf and textf2. Create a new black rectangle movieclip and place 2 instances of it on the stage. Call them example1 and example2.

Now that we have everything set, its time for coding.

First we create a new bitmap data object, set its size to colorPicker's size and make it draw the spectrum (copy the pixels). Apple this data to a bitmap and place it on the stage, over colorPicker:

var bitmap:BitmapData = new BitmapData(colorPicker.width, colorPicker.height);
bitmap.draw(colorPicker)
var image:Bitmap = new Bitmap(bitmap);
addChild(image);
image.x=colorPicker.x
image.y=colorPicker.y

Create a new ColorTransform object. We will use it to change the colors of our example rectangles. Create a new variable 'hex', it will be used to store the color that can be passed to colortransform.

GetPixel.toString(16) is what we will use to check for pixel's color. The output will have this format: #FFFFFF (white). However, sometimes it might come out without enough characters, like #0 (black), so we will need to add zeros in front of the number. Thats why we add two more variables: zeros and zerosNeeded.

var colorTransform:ColorTransform = new ColorTransform(); 
var hex;
var zeros;
var zerosNeeded;

Add 2 listeners and functions - one for mouse moving over our spectrum, and another one for clicking.

First we check if we need to add any additional zeros, then add them when changing the string.

When user moves cursor over the color picker, the text should change, 'hex' variable's value should change, the colorTransform should be changed to 'hex' and it should be applied to example rectangle.

When clicked, change the second textfield and example to the current ones.

colorPicker.addEventListener(MouseEvent.MOUSE_MOVE, lookupPixel);
function lookupPixel(MouseEvent){
 zeros=""
 zerosNeeded=6-(bitmap.getPixel(colorPicker.mouseX, colorPicker.mouseY).toString(16)).length
 trace(zerosNeeded);
 for(var i:int; i<zerosNeeded; i++){
 zeros+="0"
 }
 textf.text="#" + zeros + bitmap.getPixel(colorPicker.mouseX, colorPicker.mouseY).toString(16).toUpperCase();
 hex="0x" + bitmap.getPixel(colorPicker.mouseX, colorPicker.mouseY).toString(16);
 colorTransform.color = hex;
 example1.transform.colorTransform = colorTransform;
 }

colorPicker.addEventListener(MouseEvent.CLICK, pickPixel);
function pickPixel(MouseEvent){
 textf2.text=textf.text
 example2.transform.colorTransform = colorTransform;
 }

Thanks for reading!

1 comment:

Post a Comment