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);
}
}
![Brandon](https://i.stack.imgur.com/osGFm.jpg?s=256&g=1)
Comments
-
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 about 15 yearsI voted up, thanks for the tip. Do you know how to scale beyond 145?
-
Cristian Donoso about 15 yearsSorry, I don't how to scale the font size beyond 145
-
rakslice about 14 yearsWhen 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 over 11 years'txt.setTextFormat' does NOT change the 'txt.textHeight' when scale down. What is the solution?
-
Cilan almost 10 yearsFor the sake of confusion, please camelCase your function name, and maybe change it?