Saturday, August 14, 2010

How to create a color picker with sliders using Actionscript 3

In this tutorial you will learn how to create a different from previous tutorial color picker. This one has 3 sliders for 3 color channels.

Here's how our final product will look like:

Let's get started. Go to your components tab and create 3 sliders on the stage. Name them redSlider, greenSlider and blueSlider. In component inspector, put their minimum values to 0 and maximum to 255. This is very important step.

Make 3 textfields, name them redText, greenText and blueText. Create or find a picture you want to color. In my case, it's a black skull on transparent background. Place it on the stage, convert to movie clip and give an instance of 'picture'.

Coding time!

The whole script consists of one function. It is listened by the picture movieclip through Event.ENTER_FRAME:

picture.addEventListener(Event.ENTER_FRAME, updateColors);

The function itself:

function updateColors(Event):void{
var colorTransform:ColorTransform = new ColorTransform(0,0,0,1,redSlider.value, greenSlider.value, blueSlider.value, 0);
picture.transform.colorTransform = colorTransform;

redText.text="Red: " + redSlider.value
greenText.text="Green: " + greenSlider.value
blueText.text="Blue: " + blueSlider.value

As you can see, first we create a new ColorTransform object. It has many parameters, and they all matter. Here is the template:
ColorTransform(RedMultiplier, GreenMultiplier, BlueMultiplier, AlphaMultiplier, RedOffset, GreenOffset, BlueOffset, AlphaOffset);

The color is calculated this way (as seen on Adobe livedocs):

New red value = (old red value * redMultiplier) + redOffset
New green value = (old green value * greenMultiplier) + greenOffset
New blue value = (old blue value * blueMultiplier) + blueOffset
New alpha value = (old alpha value * alphaMultiplier) + alphaOffset

We put all color multipliers to 0, because we don't want it to depend on the previous color. We want a brand new color. This way it will equal the offset. AlphaMultiplier is 1, because we want our picture to be fully visible, and AlphaOffset is 0. All three color offsets are set to slider component values.

Then we apply the color transform to our picture. After that we just update the text fields.

And there you have it! Thanks for reading.

No comments:

Post a Comment