Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 304
Brandon Avatar asked May 01 '09 16:05

Brandon


1 Answers

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);
  }

}
like image 135
Cristian Donoso Avatar answered Oct 14 '22 13:10

Cristian Donoso