[AS3] Dynamic Text Sizing to width and numLines
by Brandt Krueger
on
Aug 12, 2008 at 5:10:02 pm
Hey folks,
Been staring at this one for a few hours now and can't seem to get all the pieces to play nice.
I have a text field that dynamically receives its .text from an XML file. I've done lots of work in the past with resizing single line text fields, but for this particular one I need it to be two lines, no matter how much text there is (within reason).
Can't seem to wrap my brain around the right combination of .width, .wordWrap, .numLines, and .size to make this happen.
Basically, I want this:
This is my really long text that I need to fit into 2 lines.
To be this:
This is my really long text that
I need to fit into 2 lines
Centered and font sized to fit in my desired area.
Anyone ever run into something like this before? Any help would be much appreciated!
General notice: from now on, I would like to ask everyone to put [AS2] or [AS3] (corresponding to the version of actionscript you are using on your project) in front of their post titles when the question is actionscript related! Please help us help you faster. Thank you.
Re: [AS3] Dynamic Text Sizing to width and numLines by Brandt Krueger on Aug 12, 2008 at 8:48:04 pm
Still playing around with it. It would be nice to avoid the setting of the various font sizes and come up with something, but that may yet be the way to go, so thanks Pieter.
In the meantime, any idea why this causes a timeout?
var container_mc:Sprite = new Sprite();
addChild(container_mc);
var maxLines:Number = 2;
var maxWidth:Number = 410;
var txt:TextField = new TextField();
txt.wordWrap = true;
txt.text = "This is a really long line of textaluffagus that I'd like to fit on "+maxLines+" lines";
txt.addEventListener(Event.ADDED_TO_STAGE, setLines);
container_mc.addChild(txt);
function setLines(event:Event):void{
while(txt.numLines>maxLines){
txt.width +=1;
}
}
Re: [AS3] Dynamic Text Sizing to width and numLines by Pieter Helsen on Aug 12, 2008 at 9:23:23 pm
numLines doesn't actually return the number of lines in the textfield, it returns the number of lines in the text. So if you have two linebreaks in your text (n) the numLines property will be set to three.
The only way to calculate the number of lines is by using my function.
Also, I found a way to deal with the size a little more intelligently.
var txt_fmt:TextFormat = new TextFormat(null, 12);
// And then, you're gonna use that textformat and just reset the size
// Like so:
txt_fmt.size--;
txt.setTextFormat(txt_fmt);
Kind regards,
Pieter
General notice: from now on, I would like to ask everyone to put [AS2] or [AS3] (corresponding to the version of actionscript you are using on your project) in front of their post titles when the question is actionscript related! Please help us help you faster. Thank you.