TextLineMetrics

Actionscript:
  1. var word:String = "TextLineMetrics are useful";
  2. var letters:Array = word.split("");
  3.  
  4. var pre:TextField;
  5. for (var i:int = 0; i<letters.length; i++){
  6.     var t:TextField = new TextField();
  7.     t.defaultTextFormat = new TextFormat("Arial", 40);
  8.     t.autoSize = TextFieldAutoSize.LEFT;
  9.     t.textColor = int(Math.random() * 0xFFFFFF);
  10.     t.text = letters[i];
  11.     if (pre){
  12.         var metrics:TextLineMetrics = pre.getLineMetrics(0);
  13.         t.x = metrics.width + pre.x;
  14.     }
  15.     pre = t;
  16.     addChild(t);
  17. }

Sometimes you need to do something to a TextField one letter at a time. One way to do this is to create a separate TextField for each letter and position them based on the TextLineMetrics object. This snippet creates textFields for a string and colors each TextField randomly.

This entry was posted in string manipulation, strings and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

5 Comments

  1. Posted April 23, 2010 at 2:53 pm | Permalink

    This post reminded me of splittextfield at greensock: http://www.greensock.com/splittextfield/

    But also useful to not use a full library when performing text operations like yours above.

  2. Posted April 23, 2010 at 6:46 pm | Permalink

    Does TextLineMetrics retain the ‘virtual’ letter spacing when placing TextFields side-by-side? For example, if I format a TextField via styleSheet, or via TextFormat, and if I copy from that textField letter by letter and place each letter within it’s own textField side by side, are those letter spacing numerics captured / retained when using TextLineMetrics? Sorry for the long questions.

  3. Posted April 24, 2010 at 10:28 am | Permalink

    @Jeff that looks cool.
    @Lex I’m not really sure … you should try and create a test to see if it works or not - because off the top of my head, I’m not really sure.

  4. Posted April 25, 2010 at 11:26 am | Permalink

    This is an alternative (note: I know yours is an example of what you can do with the metrics and note just about the example :-)) and should be a lot faster.

    var word:String=”TextLineMetrics are useful”;
    var textformat:TextFormat=new TextFormat(”Arial”,40);

    var t:TextField = new TextField();
    t.autoSize=TextFieldAutoSize.LEFT;
    t.text = word;
    addChild(t);

    for (var i:int = 0; i<word.length; i++) {
    textformat.color=int(Math.random()*0xFFFFFF);
    t.setTextFormat(textformat, i);
    }

  5. Posted April 26, 2010 at 11:41 pm | Permalink

    Really cool. Thanks for digging the new as3 apis. Now I will make my little text effect engine.

One Trackback

  1. [...] TextLineMetrics [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*