AS3 Tip

{0 notes} home

With AS3.0, we’ve been given a pretty cool new method for the TextField class: getCharBoundaries. This method returns the bounding box (in the form of a Rectangle) for a specified character in the TextField.

Here’s a way to animate a TextField to make it look as though it’s being typed, letter by letter, onto the stage:

/**
 * Create a "typing" effect on a TextField instance
 * @param	myRoot		the "root" displayObject which will parent the mask (should be the same as your TextField's parent)
 * @param	txtField	the instance of TextField to be animated
 * @param	time		the total amount of time allotted for the animation (leave blank for the default)
 */
public static function animateText(myRoot:DisplayObjectContainer, txtField:TextField, time:Number = 0):void {
	// If no time is specified, default to 0.1 second per character
	if (time == 0) time = (txtField.length * 100) / 1000;

	var txtMask:Sprite = new Sprite();
	txtField.mask = txtMask;
	// You should probably start your TextField out hidden in some way
	txtField.alpha = 1;
	txtField.visible = true;

	txtMask.x = txtField.x;
	txtMask.y = txtField.y;
	myRoot.addChild(txtMask);

	var g:Graphics = txtMask.graphics;
	g.lineStyle(0, 0, 0);

	/* Set up a timer to perform the "animation." Find out the length of time 
	 * for each letter by dividing the provided time by the length of the field */
	var maskAnim:Timer = new Timer((time * 1000)/txtField.length, txtField.length);

	var letterRect:Rectangle;
	maskAnim.addEventListener(TimerEvent.TIMER, function(e:TimerEvent) {
		// For each letter in the TextField, draw a rectangle on the mask
		letterRect = txtField.getCharBoundaries(maskAnim.currentCount-1);
		g.beginFill(0, 1);
		g.drawRect(letterRect.x, letterRect.y, letterRect.width, letterRect.height);
		g.endFill();
	});

	maskAnim.addEventListener(TimerEvent.TIMER_COMPLETE, function(e:TimerEvent) {
		// Once the animation is complete, remove and dispose of the mask
		txtField.mask = null;
		myRoot.removeChild(txtMask);
		txtMask = null;
	});

	maskAnim.start();
}
blog comments powered by Disqus