Step 1: Brief Overview
We’ll split a user defined string into an array, and then add the resulting letters to aTextField one by one using the Timer class. Step 2: Typewriter Class
Our class will bestatic, which means it doesn’t need to be instantiated using the new keyword. To access a static class member, use the name of the class instead of the name of an instance. Create a new ActionScript file and write the following code: package
{
import flash.text.TextField;
import flash.utils.Timer;
import flash.events.TimerEvent;
public final class Typewriter
{
/* Declare the variables and methods as static */
private static var chars:Array; //the characters in the string
private static var cLen:int; //length of the string
private static var tf:TextField; //textfield to which the string will be written
private static var timer:Timer; //pauses between writing each character
private static var i:int = 0; //variable used to count the written characters
public static function write(txt:String, txtField:TextField, time:Number):void
{
chars = txt.split(""); //split the string into an array of characters
cLen = chars.length + 2; //length of the string
tf = txtField; //assign tf to the text field passed to the function
timer = new Timer(time); //set time according to parameter
timer.addEventListener(TimerEvent.TIMER, writeChar);
timer.start(); //start writing function
}
private static function writeChar(e:TimerEvent):void
{
tf.appendText(chars[i]); //writes a char every time the function is called
i++; //counts the written chars
if(tf.length == cLen) //check whether string is complete
{
timer.stop();
timer.removeEventListener(TimerEvent.TIMER, writeChar); //clear timer
timer = null;
}
}
}
}
Step 3: Usage
The usage couldn’t be easier – just add theTypewriter.as class to your project folder and use the following code: import Typewriter;
Typewriter.write('Text to Write', targetTextfield, 50);
That’s it, test your movie and you’ll see your TextField using the Typewriter effect. Step 4: Example
I used the class in on this example swf so you can see the effect [...]Read more: Quick Tip: Create a Typewriter Text Effect Class
No comments:
Post a Comment