/ Published in: ActionScript 3
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
import flash.text.TextField; function scaleTextToFitInTextField( txt : TextField ):void { var f:TextFormat = txt.getTextFormat(); f.size = ( txt.width > txt.height ) ? txt.width : txt.height; txt.setTextFormat( f ); while ( txt.textWidth > txt.width - 4 || txt.textHeight > txt.height - 6 ) { f.size = int( f.size ) - 1; txt.setTextFormat( f ); } } function scaleTextFieldToFitText( txt : TextField ) : void { //the 4s take into account Flash's default padding. //If I omit them, edges of character get cut off. txt.width = txt.textWidth + 4; txt.height = txt.textHeight + 4; } //demo var tf : TextField = new TextField(); addChild( tf ); tf.border = true; tf.width = Math.random() * 400 + 30; tf.height = Math.random() * 400 + 30; tf.text = "hello there"; scaleTextToFitInTextField( tf ); scaleTextFieldToFitText( tf );