4
votes

I have a TextField with multiline and word wrap enabled, and a fixed width. I want to calculate the total height of the text inside it.

I tried using TextField.textHeight, but that gives me the height of one line. Because of the wrapping, I can't easily calculate the number of lines to multiply it with the line height. TextField.height just gives me the fixed, default height of the field, 100 pixels.

So how to do it?

3

3 Answers

4
votes

There must be a mistake in your code, since textHeight should return your TextField height , not just one line height.

1
votes

make sure you include wordWrap

this traces txt.textHeight = 135

var format:TextFormat = new TextFormat();
format.font = new Bauhaus ().fontName;

var txt:TextField = new TextField();
txt.embedFonts = true;
txt.multiline = true;
txt.defaultTextFormat = format;
txt.wordWrap = true;
txt.width = 100;
txt.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi metus diam, condimentum sagittis rutrum vitae, vehicula et velit.";
addChild(txt);

trace("txt.textHeight "+txt.textHeight);
0
votes

I found a solution from looking at Docs, and this tip.

Both of the following work perfectly for me with single-line, multi-line word-wrap (just text wrap, and \n), and multi-line no word wrap (just \n).

Short assumptive version (don't use this):

var totalLines = textField.bottomScrollV - textField.scrollV + textField.maxScrollV;
var metrics    = textField.getLineMetrics(0);
var gutter     = 2;
var actualHeight = (metrics.ascent + metrics.descent) * totalLines + (totalLines - 1) * metrics.leading + 2 * gutter;

Longer better version where lines have differing metrics (use this):

var gutter  = 2;
var totalLines = textField.bottomScrollV - textField.scrollV + textField.maxScrollV;

var actualHeight = 0;
var prevLeading = 0;
for (var i = 0; i < totalLines; i += 1)
{
    var metrics = textField.getLineMetrics(i);
    actualHeight += metrics.ascent + metrics.descent + prevLeading;
    prevLeading = metrics.leading;
}
actualHeight += 2 * gutter;

For a single line test with an inline image where textField height gives me 32, textHeight gives me 39, the calculated height (actualHeight above) is 34. For a multi-line test where height is 97.20, textHeight is 23.79, actualHeight is 97.15. This actual height includes the gutter on both sides, but strips out the trailing leading if there is any.