April 12, 2006
Flash 8: Measuring Line Widths of TextFields
While ActionScript 3.0 comes with the TextLineMetrics Class that allows you to get all kinds of information about a text selection, with Flash 8 and below you have to go all the way on your feet if you want to know the width or position of a line of text within a textfield.
Before Flash 8 the only way I know of to accomplish this was to split the whole text into single words and add up their widths. But Flash 8 offers a new way to do this which works by using a BitmapData object together with the rarely used getColorBoundsRect() method. Check out the code and a demo here:
function getLineMetrics( textfield:TextField, skipEmptyLines:Boolean ):Array
{
var rememberBorder:Boolean = textfield.border;
textfield.border = false;
var lineHeight:Number = textfield.getTextFormat().getTextExtent("W").textFieldHeight - 4;
// _global.__lineMeasureMap is used in order to cope with the flash memory leak that happens with
// bitmaps that get defined inside of functions
var bm:BitmapData = _global.__lineMeasureMap = new BitmapData(textfield._width,lineHeight,true,0);
var lines:Array = Array();
for (var i=0; i < textfield._height; i+=lineHeight )
{
bm.draw( test, new Matrix(1,0,0,1,0,-(i+2)));
var r:Rectangle = bm.getColorBoundsRect(0xff000000,0xff000000,true);
if (!skipEmptyLines || r.width>0){
r.x += textfield._x;
r.y += textfield._y + i+2;
lines.push( r);
}
bm.fillRect( bm.rectangle, 0 );
}
textfield.border = rememberBorder;
_global.__lineMeasureMap.dispose();
return lines;
}
Download getLineMetrix.fla demo here.
Posted at April 12, 2006 06:13 PM | Further reading




