PageRenderTime 43ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/nickro/greensock/text/SplitTextField.as

http://my-project-nickro.googlecode.com/
ActionScript | 343 lines | 192 code | 30 blank | 121 comment | 44 complexity | 98463f603ee6906e16c3f4b69ddb5ef4 MD5 | raw file
  1. /**
  2. * VERSION: 0.6
  3. * DATE: 1/6/2010
  4. * AS3
  5. * UPDATES AND DOCUMENTATION AT: http://blog.greensock.com
  6. **/
  7. package org.nickro.greensock.text {
  8. import flash.display.DisplayObjectContainer;
  9. import flash.display.Sprite;
  10. import flash.geom.Matrix;
  11. import flash.geom.Point;
  12. import flash.geom.Rectangle;
  13. import flash.text.TextField;
  14. import flash.text.TextFieldAutoSize;
  15. import flash.text.TextFormat;
  16. import flash.text.TextFormatAlign;
  17. import flash.text.TextLineMetrics;
  18. /**
  19. * SplitTextField makes it easy to break apart a TextField so that each character, word, or line
  20. * is in its own TextField, making complex animation simple. When you create a SplitTextField, it
  21. * seamlessly replaces the source TextField with itself (a Sprite) containing these multiple TextFields,
  22. * all conveniently stored in a <b><code>textFields</code></b> array that you can, for example,
  23. * feed to a <code>TweenMax.allFrom()</code> or loop through to create unique tweens for each character,
  24. * word or line. The SplitTextField keeps the same scale/rotation/position as the source TextField,
  25. * and you can optionally offset the registration point by a certain number of pixels on its local
  26. * x- or y-axis, which can be useful if, for example, you want to be able to scale the whole
  27. * SplitTextField from its center instead of its upper left corner. Use an onComplete in your
  28. * tween to call the SplitTextField's <code>deactivate()</code> or <code>destroy()</code> method
  29. * which will swap the original TextField back into place. <br /><br />
  30. *
  31. * @example Example AS3 code:<listing version="3.0">
  32. import org.nickro.greensock.text.SplitTextField;
  33. import org.nickro.greensock.TweenMax;
  34. import org.nickro.greensock.easing.Elastic;
  35. import org.nickro.greensock.plugins.~~;
  36. import flash.geom.Point;
  37. //split myTextField1 by characters (the default type of split)
  38. var stf1:SplitTextField = new SplitTextField(myTextField1);
  39. //tween each character down from 100 pixels above while fading in, and offset the start times by 0.05 seconds
  40. TweenMax.allFrom(stf1.textFields, 1, {y:"-100", autoAlpha:0, ease:Elastic.easeOut}, 0.05);
  41. //split myTextField2 by words
  42. var stf2:SplitTextField = new SplitTextField(myTextField2, SplitTextField.TYPE_WORDS);
  43. //explode the words outward using the physics2D feature of TweenLite/Max
  44. TweenPlugin.activate([Physics2DPlugin]);
  45. var i:int = stf2.textFields.length;
  46. var explodeOrigin:Point = new Point(stf2.width ~~ 0.4, stf2.height + 100);
  47. while (i--) {
  48. var angle:Number = Math.atan2(stf2.textFields[i].y - explodeOrigin.y, stf2.textFields[i].x - explodeOrigin.x) ~~ 180 / Math.PI;
  49. TweenMax.to(stf2.textFields[i], 2, {physics2D:{angle:angle, velocity:Math.random() ~~ 200 + 150, gravity:400}, scaleX:Math.random() ~~ 4 - 2, scaleY:Math.random() ~~ 4 - 2, rotation:Math.random() ~~ 100 - 50, autoAlpha:0, delay:1 + Math.random()});
  50. }
  51. //split myTextField3 by lines
  52. var stf3:SplitTextField = new SplitTextField(myTextField3, SplitTextField.TYPE_LINES);
  53. //slide each line in from the right, fading it in over 1 second and staggering the start times by 0.5 seconds. Then swap the original TextField back in.
  54. TweenMax.allFrom(stf3.textFields, 1, {x:"200", autoAlpha:0, onComplete:stf3.deactivate}, 0.5);
  55. </listing>
  56. *
  57. * <b>NOTES / LIMITATIONS</b><br />
  58. * <ul>
  59. * <li>Does not recognize "Auto kern" feature in Flash.</li>
  60. * <li>Positioning may be incorrect when non-standard anti-aliasing is used (like "anti-alias for readability"). Even with standard anti-aliasing, depending on the specific font you use positioning may be <i>slightly</i> off.</li>
  61. * <li>Does not work with htmlText</li>
  62. * <li>To improve performance, mouseChildren is set to false by default (you're welcome to set it to true if you need the TextFields to receive MouseEvents)</li>
  63. * <li>To avoid some bugs in the way Flash renders TextFields, when creating TextField instances
  64. * dynamically make sure you set the various properties of the TextField <b>BEFORE</b> adding
  65. * the actual text. For example, set the <code>width, height, embedFonts, autoSize, multiline,</code> and
  66. * other properties before setting the <code>text</code> property.</li>
  67. * <li>Not intended for use in Flex (use FlexSplitTextField instead)</li>
  68. * </ul><br />
  69. *
  70. * SplitTextField is a <a href="http://blog.greensock.com/club/">Club GreenSock</a> membership benefit.
  71. * You must have a valid membership to use this class without violating the terms of use. Visit
  72. * <a href="http://blog.greensock.com/club/">http://blog.greensock.com/club/</a> to sign up or get more details. <br /><br />
  73. *
  74. * <b>Copyright 2009, GreenSock. All rights reserved.</b> This work is subject to the terms in <a href="http://www.greensock.com/terms_of_use.html">http://www.greensock.com/terms_of_use.html</a> or for corporate Club GreenSock members, the software agreement that was issued with the corporate membership.
  75. *
  76. * @author Jack Doyle, jack@greensock.com
  77. */
  78. public class SplitTextField extends Sprite {
  79. /** @private **/
  80. public static const version:Number = 0.6;
  81. /** Split type: characters **/
  82. public static const TYPE_CHARACTERS:String = "characters";
  83. /** Split type: words **/
  84. public static const TYPE_WORDS:String = "words";
  85. /** Split type: lines **/
  86. public static const TYPE_LINES:String = "lines";
  87. /** @private **/
  88. private static const _propNames:Array = ["embedFonts","alpha","antiAliasType","blendMode","filters","focusRect","gridFitType","mouseEnabled","sharpness","selectable","textColor","thickness"];
  89. /** @private **/
  90. private var _splitType:String;
  91. /** @private **/
  92. private var _regOffsetX:Number;
  93. /** @private **/
  94. private var _regOffsetY:Number;
  95. /** @private **/
  96. private var _source:TextField;
  97. /** Array of TextFields resulting from the split (one for each character, word, or line based on the splitType) **/
  98. public var textFields:Array;
  99. /**
  100. * Constructor.
  101. *
  102. * @param source The source TextField that should be split apart. Remember, this TextField will be replaced in the display list with the SplitTextField (which is essentially a Sprite containing the various resulting TextFields).
  103. * @param splitType Determines the way in which the TextField is split apart - either by characters, words, or lines. Use the <code>TYPE_CHARACTERS, TYPE_WORDS,</code> and <code>TYPE_LINES</code> constants.
  104. * @param regOffsetX To offset the registration point by a certain number of pixels along its x-axis (according to the SplitTextField's internal coordinate system), use regOffsetX.
  105. * @param regOffsetY To offset the registration point by a certain number of pixels along its y-axis (according to the SplitTextField's internal coordinate system), use regOffsetY.
  106. */
  107. public function SplitTextField(source:TextField=null, splitType:String="characters", regOffsetX:Number=0, regOffsetY:Number=0) {
  108. super();
  109. _source = source;
  110. _splitType = splitType;
  111. _regOffsetX = regOffsetX;
  112. _regOffsetY = regOffsetY;
  113. this.mouseChildren = false;
  114. this.textFields = [];
  115. if (source) {
  116. update();
  117. }
  118. }
  119. /**
  120. * This static method can be used to split apart any TextField and place the resulting
  121. * TextFields into any DisplayObjectContainer. It provides the core functionality of the
  122. * SplitTextField class, but can be used apart from any instance thereof as well.
  123. *
  124. * @param source The source TextField that should be split apart. Remember, this TextField will be replaced in the display list with the SplitTextField (which is essentially a Sprite containing the various resulting TextFields).
  125. * @param splitType Determines the way in which the TextField is split apart - either by characters, words, or lines. Use the <code>TYPE_CHARACTERS, TYPE_WORDS,</code> and <code>TYPE_LINES</code> constants.
  126. * @param container The DisplayObjectContainer into which the new TextFields should be placed.
  127. * @param offset Determines the offset x/y of the new TextFields. By default, the TextFields will be positioned in the container as though the container's registration point was aligned perfectly with the source TextField's. The source TextField's scale, rotation, and x/y coordinates will have no effect whatsoever.
  128. * @return Array of TextFields resulting from the split.
  129. */
  130. public static function split(source:TextField, spitType:String="characters", container:DisplayObjectContainer=null, offset:Point=null):Array {
  131. if (container == null) {
  132. container = source.parent;
  133. }
  134. if (offset == null) {
  135. offset = new Point(0,0);
  136. }
  137. var index:uint = (source.parent == container) ? source.parent.getChildIndex(source) : container.numChildren;
  138. var segments:Array;
  139. var cnt:uint = 0;
  140. var linesTotal:uint = source.numLines;
  141. var bounds:Rectangle = source.getBounds(source); //TextFields created in the Flash IDE usually have a -2 pixel offset, dynamically-created ones have a 0 pixel offset, and on the Mac, they can vary wildly! So we getBounds() to figure out how to compensate.
  142. var y:Number = bounds.y + offset.y;
  143. var fields:Array = [];
  144. var format:TextFormat, tf:TextField, x:Number, line:uint, i:uint, j:int, l:uint, text:String, totalSegments:uint, charOffset:uint, lineMetrics:TextLineMetrics, ascentDiff:Number;
  145. for (line = 0; line < linesTotal; line++) {
  146. text = source.getLineText(line);
  147. charOffset = source.getLineOffset(line);
  148. lineMetrics = source.getLineMetrics(line);
  149. if (source.text.length <= charOffset) { //sometimes Flash adds an extra line to the end unnecessarily
  150. continue;
  151. }
  152. //There are bugs in TextField.getCharBoundaries() that incorrectly returned null results occassionally, so we must figure it out using the align of the line.
  153. format = source.getTextFormat(charOffset, charOffset + 1);
  154. if (format.align == "left") {
  155. x = bounds.x + offset.x;
  156. } else if (format.align == "center") {
  157. x = bounds.x + offset.x - 2 + (source.width - lineMetrics.width) * 0.5;
  158. } else {
  159. x = bounds.x + offset.x - 4 + (source.width - lineMetrics.width);
  160. }
  161. if (spitType == TYPE_CHARACTERS) {
  162. segments = text.split("");
  163. } else if (spitType == TYPE_WORDS) {
  164. segments = text.split(" ").join("~#$ ~#$").split("~#$");
  165. } else {
  166. segments = [text];
  167. }
  168. totalSegments = segments.length;
  169. for (i = 0; i < totalSegments; i++) {
  170. if (segments[i].length == 0) {
  171. continue;
  172. }
  173. tf = new TextField();
  174. j = _propNames.length;
  175. while (j--) {
  176. tf[_propNames[j]] = source[_propNames[j]];
  177. }
  178. tf.autoSize = TextFieldAutoSize.LEFT;
  179. tf.selectable = tf.multiline = tf.wordWrap = false;
  180. tf.text = segments[i];
  181. l = segments[i].length;
  182. for (j = 0; j < l; j++) {
  183. format = source.getTextFormat(charOffset, charOffset + 1);
  184. charOffset += 1;
  185. format.align = TextFormatAlign.LEFT;
  186. tf.setTextFormat(format, j, j + 1);
  187. }
  188. tf.x = x;
  189. tf.y = y;
  190. ascentDiff = lineMetrics.ascent - tf.getLineMetrics(0).ascent; //if different formatting is used on the same line (for example, a 50px letter next to a 12px letter), we must adjust the y position to make the baselines match.
  191. if (ascentDiff) {
  192. tf.y += ascentDiff;
  193. }
  194. x += tf.textWidth;
  195. if (segments[i] != " ") {
  196. fields[cnt++] = tf;
  197. }
  198. }
  199. y += lineMetrics.height;
  200. }
  201. i = fields.length;
  202. while (i--) {
  203. container.addChildAt(TextField(fields[i]), index);
  204. }
  205. if (source.parent) {
  206. source.parent.removeChild(source);
  207. }
  208. return fields;
  209. }
  210. /** When a SplitTextField is activated, it takes the place of the source TextField in the display list. **/
  211. public function activate():void {
  212. this.activated = true;
  213. }
  214. /**
  215. * When a SplitTextField is deactivated, it swaps the source TextField back into the display list.
  216. * This makes it simple to animate the SplitTextField's contents with TweenLite/Max and then use
  217. * an onComplete to call deactivate() which will swap the original (source) TextField back into place.
  218. **/
  219. public function deactivate():void {
  220. this.activated = false;
  221. }
  222. /**
  223. * Deactivates the SplitTextField (swapping the original TextField back into place) and
  224. * deletes all child TextFields that resulted from the split operation, and nulls references to
  225. * the source so that it's eligible for garbage collection.
  226. **/
  227. public function destroy():void {
  228. this.activated = false;
  229. clear();
  230. _source = null;
  231. }
  232. /** @private **/
  233. private function update():void {
  234. clear();
  235. if (_source.parent) {
  236. var p:DisplayObjectContainer = _source.parent;
  237. p.addChildAt(this, p.getChildIndex(_source));
  238. p.removeChild(_source);
  239. }
  240. var m:Matrix = _source.transform.matrix;
  241. if (_regOffsetX != 0 || _regOffsetY != 0) {
  242. var point:Point = m.transformPoint(new Point(_regOffsetX, _regOffsetY));
  243. m.tx = point.x;
  244. m.ty = point.y;
  245. }
  246. this.transform.matrix = m;
  247. this.textFields = split(_source, _splitType, this, new Point(-_regOffsetX, -_regOffsetY));
  248. }
  249. /** @private **/
  250. private function clear():void {
  251. var i:int = this.textFields.length;
  252. while (i--) {
  253. this.removeChild(this.textFields[i]);
  254. }
  255. this.textFields = [];
  256. }
  257. /** The source TextField that gets split apart. **/
  258. public function get source():TextField {
  259. return _source;
  260. }
  261. public function set source(tf:TextField):void {
  262. _source = tf;
  263. update();
  264. }
  265. /** Determines the way in which the source TextField is split apart - either by characters, words, or lines. Use the <code>TYPE_CHARACTERS, TYPE_WORDS,</code> and <code>TYPE_LINES</code> constants. **/
  266. public function get splitType():String {
  267. return _splitType;
  268. }
  269. public function set splitType(type:String):void {
  270. _splitType = type;
  271. update();
  272. }
  273. /** To offset the registration point by a certain number of pixels along its x-axis (according to the SplitTextField's internal coordinate system), use regOffsetX. **/
  274. public function get regOffsetX():Number {
  275. return _regOffsetX;
  276. }
  277. public function set regOffsetX(x:Number):void {
  278. _regOffsetX = x;
  279. update();
  280. }
  281. /** To offset the registration point by a certain number of pixels along its y-axis (according to the SplitTextField's internal coordinate system), use regOffsetY. **/
  282. public function get regOffsetY():Number {
  283. return _regOffsetY;
  284. }
  285. public function set regOffsetY(y:Number):void {
  286. _regOffsetY = y;
  287. update();
  288. }
  289. /** When a SplitTextField is activated, it replaces the source TextField in the display list. When it is deactivated, it swaps the source TextField back into place **/
  290. public function get activated():Boolean {
  291. return Boolean(this.parent != null);
  292. }
  293. public function set activated(b:Boolean):void {
  294. if (_source == null) {
  295. return;
  296. }
  297. if (_source.parent && b) {
  298. _source.parent.addChildAt(this, _source.parent.getChildIndex(_source));
  299. _source.parent.removeChild(_source);
  300. } else if (this.parent && !b) {
  301. this.parent.addChildAt(_source, this.parent.getChildIndex(this));
  302. this.parent.removeChild(this);
  303. }
  304. }
  305. }
  306. }