Tuesday, March 1, 2011

Format user selected text using AS3

In this tutorial we will learn how to let the user format text in an editable input text field by selecting a part of the text and then selecting a colour.

Basically, we're going to make a little WYSIWYG (what you see is what you get) text editor in AS3. It is going to look like this:

First of all, create an input text field and call it inpf. Then add a ColorPicker component and call it colPicker.

Here is the full code:

import flash.text.TextFormat;
import fl.controls.ColorPicker;
import fl.events.ColorPickerEvent;

inpf.text = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.";

var myFormat:TextFormat = new TextFormat();
myFormat.color = 0x000000;

colPicker.addEventListener(ColorPickerEvent.CHANGE, changeColor);

function changeColor(ColorPickerEvent):void
myFormat.color = colPicker.selectedColor;
inpf.setTextFormat(myFormat, inpf.selectionBeginIndex, inpf.selectionEndIndex);

Basically, what we do is create a text format, which we change and apply to the text every time we change the color in the component. We use the setTextFormat() method to change the color, which has 3 parameters - format, start index and end index (we get those based on the current selection in the text field).

And that's how you do it.

Thanks for reading!

No comments:

Post a Comment