Fix: dynamically determining / setting the width of text in a textfield created with the Flash IDE

Posted on February 18, 2010

0


There is a weird behavior if not bug I found in Flash 10.

When you want to get the width of the text within an existing textfield placed in a MovieClip via the Flash IDE, you might assume the following would work:

var textField:TextField=textfieldonStage // My textfield on stage
textField.autoSize="left" // Does not expand the textfield to the right when it does not fit
textField.text="My text to measure" // The text which is longer than the text field
trace("text width "+textField.width) // Returns the width of the text field

This is what happens:

  1. The text is wrapped to the next line
  2. The text field does not resize in width
  3. You get the width of the text field, not the text itself

Different behavior from text field created with code

When you render the text in a textfield created with code it DOES behave as expected.

Workaround

var textField:TextField=textfieldonStage // Text field on stage
textField.text="My text to measure" // Text to measure
trace("text width "+textField.textWidth) // Returns the width of the visible text
textField.width=1000 // Sets the text field to such a width that all text is visible
textField.width=textField.textWidth+10 // Sets the text field to the actual width + margin
trace("textField width  "+textField.textWidth) // Returns the "correct" width of the text

Explenation

textField.textWidth only returns the width of the visible text.

So if part of the text is “hidden” as the text field is smaller than the text to render, it returns the width of the textfield, not of the text in the text field.

To bypass this behavior, we set the width of the text field to 1000 or more, so that all text is rendered and can be measured.

Secondly, the returnvalue of textWidth can be smaller than the actual rendered width of the text. So we add a “margin” to the new length.

Advertisements
Posted in: Workarounds