How to Auto-resize font size to fit text box height / width?

25,381

AS3 sample function. You should call it anytime your TextField's content changes

function Autosize(txt:TextField):void 
{
  //You set this according to your TextField's dimensions
  var maxTextWidth:int = 145; 
  var maxTextHeight:int = 30; 

  var f:TextFormat = txt.getTextFormat();

  //decrease font size until the text fits  
  while (txt.textWidth > maxTextWidth || txt.textHeight > maxTextHeight) {
    f.size = int(f.size) - 1;
    txt.setTextFormat(f);
  }

}
Share:
25,381
Brandon
Author by

Brandon

Linked In

Updated on July 09, 2022

Comments

  • Brandon
    Brandon almost 2 years

    I am trying to have text automatically size its font to fill an entire text component.

    My current approach is to set font size as a function of the number of text characters and the text components height and width but I can't find the right coefficients to make this work nicely.

    Is there a simpler or more elegant way?

    Does truncateToFit work on Text? I read somewhere that it doesn't work well.

    Edit: I forgot to mention that I would like it to scale beyond the max font size (which is 127 i believe). How is this done? scaleX?

  • Brandon
    Brandon about 15 years
    I voted up, thanks for the tip. Do you know how to scale beyond 145?
  • Cristian Donoso
    Cristian Donoso about 15 years
    Sorry, I don't how to scale the font size beyond 145
  • rakslice
    rakslice about 14 years
    When doing goal-seeking in a UI toolkit like this, you might want to put in a safeguard in so that if your changes in the input value aren't actually affecting the output value (say due to a change in toolkit behaviour in some situation), you catch it and give up, to avoid an infinite loop.
  • Katax Emperore
    Katax Emperore over 11 years
    'txt.setTextFormat' does NOT change the 'txt.textHeight' when scale down. What is the solution?
  • Cilan
    Cilan almost 10 years
    For the sake of confusion, please camelCase your function name, and maybe change it?