package site.fx { /** * @author adapted from Josh Tynjala */ import flash.events.Event; import flash.events.EventDispatcher; import flash.events.TimerEvent; import flash.text.TextField; import flash.text.TextFormat; import flash.utils.Timer; import vegas.commands.IAsyncCommand; import vegas.events.CommandEvent; public class Decrypto extends EventDispatcher implements IAsyncCommand { private var __tf:TextField; private var __text:String; private var __letterPerIteration:int; private var __index:int; private var __timer:Timer; private var __tfAutoSize:String; private var __tfTextFormat:TextFormat; // If set to true, will always choose a spaceduring randomization when it encounters a space in the original text. This can help the aesthetics when displaying multiple lines. private var __keepSpaces:Boolean = false; /** * Applies a typewriter animation on target textField */ public function Decrypto(tf:TextField, text:String, letterPerIteration:int = 1, tempoMs:Number = 50):void { __tf = tf; __tfAutoSize = __tf.autoSize; __tfTextFormat = __tf.getTextFormat(); __tf.text = ''; reset(text, letterPerIteration, tempoMs); } public function reset(text:String, letterPerIteration:int = 1, tempoMs:Number = 50):void { __text = text; __letterPerIteration = letterPerIteration; if (__timer == null){ __timer = new Timer(tempoMs, 0); __timer.addEventListener(TimerEvent.TIMER, render); } else{ endTimer(true); __timer.delay = tempoMs; __timer.repeatCount = Math.ceil(text.length / letterPerIteration); } } public function isRunning():Boolean { return __timer.running; } public function execute(e:Event = null):void { endTimer(true); __timer.start(); } private function endTimer(reset:Boolean = false):void { __timer.stop(); if (reset){ __index = 0; } } private function render(e:Event = null):void { if (__index > __text.length){ __tf.text = __text; endTimer(true); dispatchEvent(new CommandEvent(CommandEvent.COMPLETE)); } else{ __tf.text = __text.substr(0, __index) + randomChars(__text.substr(__index)); __index += __letterPerIteration; } __tf.autoSize = __tfAutoSize; __tf.setTextFormat(__tfTextFormat); } /** * Generates a string of the specified length containing random characters in the character code range 33 to 126. */ private function randomChars(value:String):String { var out:String = "", count:int = value.length; for (var i:int = 0; i < count; i++) // For best results on word wrapped textfields, spaces should be kept in the same locations. A monospaced font makes it even better. out += (__keepSpaces && value.charAt(i) == " ") ? ' ' : String.fromCharCode(int(33 + Math.random() * 93)); return out; } } }