views:

4548

answers:

2

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?

A: 

I suspect there's something in gumbo's new text controls that would be super helpful, but I haven't played with them much yet : http://opensource.adobe.com/wiki/display/flexsdk/Gumbo+Text+Primitives

Otherwise, when I've had to do this before unfortunately, I've been stuck sorta using scrollV / maxScrollV to detect when my text got too big, and it involved for loops and decreasing / increasing the size of the text as necessary. It's not very pretty.

quoo
+2  A: 

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

}
Cristian Donoso
I voted up, thanks for the tip. Do you know how to scale beyond 145?
Brandon
I meant the max font size.
Brandon
Sorry, I don't how to scale the font size beyond 145
Cristian Donoso
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.
rakslice