actionscript-3flash-cs5

How do I change the width of a TextField without stretching the text?


I used to know how to do this, so, I KNOW it's possible, but I can't figure it out again. I'm altering the width of my TextField by setting the width property but that warps the text. I want to alter the width of the text field WITHOUT altering the way the font looks (obviously). I believe it has something to do with autoText or some such idiocy (why would I EVER want to warp my text?!) but I just can't recall.

myField.width = 100; // if the original width was 50 this simply stretches the field to 100, rather than adding 50 pixels into which characters can be drawn.

TIA


Solution

  • I am guessing your problem is TextField.defaultTextFormat.

    just setup a TextFormat object then on your text field setup the default text format and it should keep the text format no matter what you do to it.

    You see when you change pretty much anything about a text field the text formatting gets reset and you have to reapply it. However if you setup the default text format it will take care of that automatically.

    Here is a dirty little prototype.

    package src 
    {
        import flash.display.Sprite;
        import flash.events.Event;
        import flash.events.MouseEvent;
        import flash.text.TextField;
        import flash.text.TextFormat;
    
        public class Main extends Sprite 
        {
            private var tx:TextField;
            private var txf:TextFormat;
    
            public function Main() 
            {
                addEventListener(Event.ADDED_TO_STAGE, initMain);
            }
    
            private function initMain(e:Event):void 
            {
                removeEventListener(Event.ADDED_TO_STAGE, initMain);
    
                // setup a text format so you can keep your text the same all the time.
                txf = new TextFormat('Arial', 12, 0x000000);
    
                tx = new TextField();
                tx.width = 50;
                tx.text = "I want this text not to wrap so it will be resized at runtime."
    
                // Turned this on for testing purposes only.
                tx.wordWrap = true;
    
                tx.defaultTextFormat = txf;     // This line is the x factor most likely.
    
                tx.x = 100;
                tx.y = 100;
    
                addChild(tx);
    
                stage.addEventListener(MouseEvent.CLICK, toggleTextFieldSize, false, 0 ,true);
            }
    
            private function toggleTextFieldSize(e:MouseEvent):void 
            {
                if (tx.width == 50)
                {
                    tx.width = 400;
                }
                else
                {
                    tx.width = 50;
                }
            }
    
        }
    
    }
    

    Hope this is what you were looking for.