Actionscript: Finding the Width of the First Line in a Dynamic Text Field

This is so ugly (or is it?) that I had to post it.

How does one find the width of the first line of a multi-line dynamic text field via Actionscript (AS2, specifically)? I couldn’t find a good solution to this via the usual forums, so I did it myself.

Here’s what I came up with. Pass in the string from the dynamic text field.

function getFirstLineWidth(_str:String):Number
{
	var firstLineWidth = 0;

	var wordArray:Array = new Array();
	wordArray = _str.split(" ");

	// "test_text" is a dummy text field on the stage. It must be
	//  the same width as the text field we're trying to measure.
	// It may be better to create a new text field on the fly then
	//  destroy it, but I needed to run this function a lot and wanted
	//  avoid the overhead.
	test_text._width = _textFieldWidth;
	test_text.text = "";

	while(wordArray.length > 0)
	{
		test_text.text += wordArray.shift() + " ";

		// Once the text goes to two lines, return the last width we recorded
		if(test_text.textHeight <= singleLineTextHeight)
		{
			firstLineWidth = test_text.textWidth;
		}
		else
		{
			break;
		}
	}

	return firstLineWidth;
}

Leave a Reply