Flash AS3 detect undesired line break in TextField wordWrap is true.

by troy on June 9, 2011

Flash inserts silent line breaks when you tell it wordWrap = true. Visually it's easy to see the break, but this new line is not reflected in either the htmlText or text, so how do you find it? Turns out you have to iterate over both the string and the textfield looking for where they word's lineindex is no longer the same.

var brokenWord : Boolean = false;
var lii : Number = 0;
var lcc : String;
for (var ci : int = 0;ci < _lbl.length;ci++) {
var cc : String = _lbl.charAt(ci);
var li : Number = _label_txt.getLineIndexOfChar(ci);
if(li != lii) {
// trace("New Line");
if(lcc != " " && lcc != "\r" && lcc != "\n") {
// trace(" broken word!");
brokenWord = true;
lii = li;
lcc = cc;
// trace(cc + " " + li);

Knowing this is useful as when loading text dynamically into a small area, that contains an occasional long word, you want to be large to be readable, a qualified url (e.g. http://www.troyworks.com/some-long-article) is in and you want people to be able to write and remember it. The desired behavior in that case might be either to widen the TextField or adjust the font size smaller so it fits.


Rendering text with fonts is computationally very expensive, all the vectors, kerning etc.

1) Flash sometimes takes about a frame for changes in format (e.g. TextFormat) to take effect/settle. This means you need to change what used to be a synchronous operation to an asynch one, personally I just listen to onEnterFrame as I think there is some background magic that synchs to that. It's only ever taken 1 frame for things to get back to what I asked.

2) Flash tries to conserve this compution for better performance, so is "smart" about calculating text until both the textField is added to stage and is visible. Which in my case trying to layout a textfield prior to showing it was exactly what I didn't need. Two workarounds are moving the textfield off visible stage (e.g. -1000, -1000) or masking it/alpha =0;