TextField fit to size

This is one function that should be in every flash developer’s toolbox. I’m so over adjusting textfields and font sizes to fit different lengths of content. There had to be better way I thought. How about a one size fits all solution. The function below uses a while loop to reduce the font size of the textfield one pt at a time until the text fits within the bounds of the width and height. Its almost too easy.

public static function fitToSize(txt : TextField, maxWidth:Number=-1, maxHeight:Number=-1) : void {
			var maxTextWidth : int = maxWidth > 0 ? maxWidth : txt.width;
			var maxTextHeight : int = maxHeight > 0 ? maxHeight : txt.height; 

			var f : TextFormat = txt.getTextFormat();

			while (txt.textWidth > maxTextWidth || txt.textHeight > maxTextHeight) {
				f.size = int(f.size) - 1;

Click on the stage below to view an example.

This movie requires Flash Player 10