Actionscript:
-
var word:String = "TextLineMetrics are useful";
-
var letters:Array = word.split("");
-
-
var pre:TextField;
-
for (var i:int = 0; i<letters.length; i++){
-
var t:TextField = new TextField();
-
t.defaultTextFormat = new TextFormat("Arial", 40);
-
t.autoSize = TextFieldAutoSize.LEFT;
-
t.textColor = int(Math.random() * 0xFFFFFF);
-
t.text = letters[i];
-
if (pre){
-
var metrics:TextLineMetrics = pre.getLineMetrics(0);
-
t.x = metrics.width + pre.x;
-
}
-
pre = t;
-
addChild(t);
-
}
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.
5 Comments
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.
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.
@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.
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);
}
Really cool. Thanks for digging the new as3 apis. Now I will make my little text effect engine.
One Trackback
[...] TextLineMetrics [...]