Quick Bit of Code: Using ColorPicker Component (AS3)

This little example comes from a recent freelance project I was working on. The task was to switch the colour of both a TextArea and a MovieClip that were already placed on the stage. This is the first time I had a reason to use the colorPicker component, and for a first time around it was a pretty darn easy to use.

Here’s what it does:
The colorPicker is disabled at first because there’s nothing to change the colour of if you don’t have the text or MovieClip selected. Once one is selected (Most likely the TextArea being that you’re asked to type in it), it becomes active and displays the current colour assigned to the object you selected.

If you click on the background MovieClip, it becomes the currently selected item and the colorPicker’s selection changes its colour instead. Pretty simple, huh?

[kml_flashembed movie=”http://www.valhead.com/blog/v_samples/colorPicker/cpTest2.swf” height=”200″ width=”550″ /]


The Code

import fl.events.ColorPickerEvent;
import fl.controls.ColorPicker;

/*variables to track the currently selected object and it’s colour.
we start with black on white.*/
var currentSelect:Object;
var currentCols:Array = new Array(“0xFFFFFF”,”0x000000″);

//a TextFormat is needed to be able to change the appearance of our TextArea on the stage.
var typeFormat:TextFormat = new TextFormat();

//initial state of the colorPicker
cp.selectedColor = 0x000000;
cp.enabled = false;

//listeners set up
typeBox.addEventListener(MouseEvent.CLICK, setSelect);
typeText.addEventListener(MouseEvent.CLICK, setSelect);

//keep track which of our two objects is currently selected
function setSelect(e:MouseEvent):void {
currentSelect = e.target;

if (currentSelect.name == “typeBox”) {
cp.enabled = true;
cp.selectedColor = currentCols[0];

}else if (currentSelect.name == “typeText”) {
cp.enabled = true;
cp.selectedColor = currentCols[1];

//change the colour of the selected object
function changeCol(event:ColorPickerEvent):void {
if (currentSelect.name == “typeBox”) {
var myTransform:ColorTransform = new ColorTransform();
myTransform.color = event.target.selectedColor;
typeBox.transform.colorTransform = myTransform;
currentCols[0] = event.target.selectedColor;

}else if (currentSelect.name == “typeText”) {
typeFormat.color = event.target.selectedColor;
currentCols[1] = event.target.selectedColor;

The Source


Have a comment or question? Find me on twitter or email me.