PageRenderTime 127ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/!src/com/greensock11.2/text/SplitTextField.as

https://github.com/tluczyns/tluczyns-as3-base
ActionScript | 344 lines | 193 code | 30 blank | 121 comment | 45 complexity | a498831fdbc1a7d0f2aa7954abc94b23 MD5 | raw file
  1. /**
  2. * VERSION: 0.62
  3. * DATE: 2010-03-05
  4. * AS3
  5. * UPDATES AND DOCUMENTATION AT: http://www.greensock.com/splittextfield/
  6. **/
  7. package com.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 com.greensock.text.SplitTextField;
  33. import com.greensock.TweenMax;
  34. import com.greensock.easing.Elastic;
  35. import com.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 2010, 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.62;
  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. format.leading = 0;
  187. tf.setTextFormat(format, j, j + 1);
  188. }
  189. tf.x = x;
  190. tf.y = y;
  191. 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.
  192. if (ascentDiff) {
  193. tf.y += ascentDiff;
  194. }
  195. x += tf.textWidth;
  196. if (segments[i] != " " || format.underline) {
  197. fields[cnt++] = tf;
  198. }
  199. }
  200. y += lineMetrics.height;
  201. }
  202. i = fields.length;
  203. while (i--) {
  204. container.addChildAt(TextField(fields[i]), index);
  205. }
  206. if (source.parent) {
  207. source.parent.removeChild(source);
  208. }
  209. return fields;
  210. }
  211. /** When a SplitTextField is activated, it takes the place of the source TextField in the display list. **/
  212. public function activate():void {
  213. this.activated = true;
  214. }
  215. /**
  216. * When a SplitTextField is deactivated, it swaps the source TextField back into the display list.
  217. * This makes it simple to animate the SplitTextField's contents with TweenLite/Max and then use
  218. * an onComplete to call deactivate() which will swap the original (source) TextField back into place.
  219. **/
  220. public function deactivate():void {
  221. this.activated = false;
  222. }
  223. /**
  224. * Deactivates the SplitTextField (swapping the original TextField back into place) and
  225. * deletes all child TextFields that resulted from the split operation, and nulls references to
  226. * the source so that it's eligible for garbage collection.
  227. **/
  228. public function destroy():void {
  229. this.activated = false;
  230. clear();
  231. _source = null;
  232. }
  233. /** @private **/
  234. private function update():void {
  235. clear();
  236. if (_source.parent) {
  237. var p:DisplayObjectContainer = _source.parent;
  238. p.addChildAt(this, p.getChildIndex(_source));
  239. p.removeChild(_source);
  240. }
  241. var m:Matrix = _source.transform.matrix;
  242. if (_regOffsetX != 0 || _regOffsetY != 0) {
  243. var point:Point = m.transformPoint(new Point(_regOffsetX, _regOffsetY));
  244. m.tx = point.x;
  245. m.ty = point.y;
  246. }
  247. this.transform.matrix = m;
  248. this.textFields = split(_source, _splitType, this, new Point(-_regOffsetX, -_regOffsetY));
  249. }
  250. /** @private **/
  251. private function clear():void {
  252. var i:int = this.textFields.length;
  253. while (i--) {
  254. this.removeChild(this.textFields[i]);
  255. }
  256. this.textFields = [];
  257. }
  258. /** The source TextField that gets split apart. **/
  259. public function get source():TextField {
  260. return _source;
  261. }
  262. public function set source(tf:TextField):void {
  263. _source = tf;
  264. update();
  265. }
  266. /** 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. **/
  267. public function get splitType():String {
  268. return _splitType;
  269. }
  270. public function set splitType(type:String):void {
  271. _splitType = type;
  272. update();
  273. }
  274. /** 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. **/
  275. public function get regOffsetX():Number {
  276. return _regOffsetX;
  277. }
  278. public function set regOffsetX(x:Number):void {
  279. _regOffsetX = x;
  280. update();
  281. }
  282. /** 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. **/
  283. public function get regOffsetY():Number {
  284. return _regOffsetY;
  285. }
  286. public function set regOffsetY(y:Number):void {
  287. _regOffsetY = y;
  288. update();
  289. }
  290. /** 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 **/
  291. public function get activated():Boolean {
  292. return Boolean(this.parent != null);
  293. }
  294. public function set activated(b:Boolean):void {
  295. if (_source == null) {
  296. return;
  297. }
  298. if (_source.parent && b) {
  299. _source.parent.addChildAt(this, _source.parent.getChildIndex(_source));
  300. _source.parent.removeChild(_source);
  301. } else if (this.parent && !b) {
  302. this.parent.addChildAt(_source, this.parent.getChildIndex(this));
  303. this.parent.removeChild(this);
  304. }
  305. }
  306. }
  307. }