Chapter 17 Example 11

by actionscriptbible
♥0 | Line 35 | Modified 2009-06-29 13:33:25 | MIT License
play

ActionScript3 source code

/**
 * Copyright actionscriptbible ( http://wonderfl.net/user/actionscriptbible )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/c6Rt
 */

package {
  import flash.display.Sprite;
  import flash.events.MouseEvent;
  import flash.text.*;

  public class ch17ex11 extends Sprite {
    protected var tf:TextField;
    protected const RED:TextFormat = new TextFormat("_serif", 28, 0xff0000);
    protected const BLACK:TextFormat = new TextFormat("_serif", 28, 0);
    
    public function ch17ex11()
    {
      tf = new TextField();
      tf.multiline = true;
      tf.wordWrap = true;
      tf.width = 450;
      tf.autoSize = TextFieldAutoSize.LEFT;
      tf.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
      tf.addEventListener(MouseEvent.MOUSE_OUT, onMouseOut);
      tf.defaultTextFormat = BLACK;
      tf.text = "Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, 'and what is the use of a book,' thought Alice 'without pictures or conversation?'"

      addChild(tf);
    }
    
    protected function onMouseMove(mouseEvent:MouseEvent):void {
      var charInText:int = tf.getCharIndexAtPoint(10, tf.mouseY);
      if (charInText == -1) return;
      var lineIndex:int = tf.getLineIndexOfChar(charInText);
      var firstCharIndex:int = tf.getLineOffset(lineIndex);
      var lastCharIndex:int = firstCharIndex + tf.getLineLength(lineIndex);
  
      //we want to set all the TextField to black except
      //the text underneath the mouse
      tf.setTextFormat(BLACK);
      tf.setTextFormat(RED, firstCharIndex, lastCharIndex);
    }
    
    protected function onMouseOut(mouseEvent:MouseEvent):void {
      tf.setTextFormat(BLACK);
    }
  }
}