Action Script 3: Scaling fonts for text in a TextField

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.

About tc

tc is a Hull based Computer Programmer with over 15 years experience in Software Development. He has developed countless Multi-Tear Desktop Applications and web applications for business in both the UK and abroad. Currently tc spends most of his time developing web sites / applications in PHP and desktop software in C#
This entry was posted in AS3 and tagged . Bookmark the permalink.

Comments are closed.