Using multiLine and TextMetrics: set the characters in the line underneath the user's mouse to red. : MouseEvent « TextField « Flash / Flex / ActionScript






Using multiLine and TextMetrics: set the characters in the line underneath the user's mouse to red.

 
package
{
import flash.display.Sprite;

import flash.text.TextField;
import flash.events.MouseEvent;
import flash.text.TextFormat;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
public class Main extends Sprite
{
    private var multilineField:TextField;
    private var redFormat:TextFormat;
    private var blackFormat:TextFormat;

    public function Main()
    {
        stage.align = StageAlign.TOP_LEFT;
        stage.scaleMode = StageScaleMode.NO_SCALE;

        redFormat = new TextFormat();
        redFormat.color = 0xFF0000;

        blackFormat = new TextFormat();
        blackFormat.color = 0x000000;

        multilineField = new TextField();
        multilineField.multiline = true;
        multilineField.wordWrap = true;
        multilineField.height = 400;
        multilineField.width = 400;
        multilineField.mouseEnabled = true;
        multilineField.addEventListener(MouseEvent.MOUSE_MOVE, 
            getMouseOverLine);
        multilineField.addEventListener(MouseEvent.MOUSE_OUT, 
            getMouseOutLine);
        multilineField.text = "Returns .";

        addChild(multilineField);
    }

    private function getMouseOverLine(mouseEvent:MouseEvent):void
    {
        var characterInLine:int = multilineField.getCharIndexAtPoint(10, mouseEvent.stageY);
        if(characterInLine != -1) {
            var lineIndex:int =  multilineField.getLineIndexOfChar(characterInLine);

            var firstCharIndex:int = multilineField.getLineOffset(lineIndex);

            var lastCharIndex:int = firstCharIndex + multilineField.getLineLength(lineIndex);

            multilineField.setTextFormat(blackFormat); 
            multilineField.setTextFormat(redFormat,firstCharIndex, lastCharIndex);
        }
    }

    private function getMouseOutLine(mouseEvent:MouseEvent):void
    {
        multilineField.setTextFormat(blackFormat);
    }
}
}

        








Related examples in the same category

1.Add mouse click listener to TextField
2.Disappearing TextField
3.Working with Advanced Text Layout
4.Highlight a paragraph when the user clicks a character
5.Drag and drop text
6.To remove the highlight when the mouse moves away from both text fields, we would first register both text fields to receive the MouseEvent.MOUSE_OUT event
7.Clickable TextField
8.Unicode characters