Quite a few times in AS3 I need dynamic text in a TextField control to scale while the solution is quite simple finding the method was time consuming. Essentially we need to call setTextFormat on the TextField control for it to recalculate textHeight and textWidth, thus allowing us to discover weather all the content of the TextField object will be visible.
Setting the defaultTextFormat.size member on its own will not cause textHeight or textWidth to be recalculated – indeed it may not even be reflected by the TextField when it is rendered.
Below is a simple example of an override of TextField control which will scale its font accordingly (download)
package
{
import flash.text.TextField;
import flash.text.TextFormat;
public class ScaleTextField extends TextField
{
public function ScaleTextField()
{
}
public override function set text(val:String):void
{
super.text = val;
var tf:TextFormat = this.getTextFormat();
if(this.textHeight>(this.height-4) || this.textWidth>this.width)
{
// Scale down
while((this.textHeight>(this.height-4) || this.textWidth>this.width) && int(tf.size)>1)
{
tf.size = int(tf.size)-1;
this.setTextFormat(tf);
}
}else
{
// Scale up
while(this.textHeight<(this.height-4) && this.textWidth<this.width)
{
tf.size = int(tf.size)+1;
this.setTextFormat(tf);
}
tf.size = int(tf.size)-1;
this.setTextFormat(tf);
}
}
}
}
Of course for the starling framework you only need change the import statments as appropriate.



