mustafa
mustafa

Reputation: 745

actionscrip3 textfield sizeing end centering

I am trying to get some words from xml and put them an the stage side by side in the center of the stage. I achieved this by the code below. I auto resize textfield according to text inside. But this time there comes space between words. What I accomplish is to have autoresized and adjacent words without space between them. But I could not solve the problem. Could you please help me to solve it. Thanks in advance

                var partsWidth=100;              
                var wordTf = new TextField();
                wordTf.name =thispart;
                wordTf.text =thispart;
                wordTf.width=partsWidth;
                xStartPoint=stage.stageWidth / 2  -  (numberOfWords * partsWidth )/2;
                wordTf.height=partsHeight;
                wordTf.x= xStartPoint + (index * partsWidth) ;
                wordTf.y=150;
                wordTf.background=true;
                wordTf.backgroundColor = 0xe3e3e3;

                wordTf.border = true;
                var myFormat:TextFormat = new TextFormat();
                    myFormat.size = 16;
                    myFormat.align = TextFormatAlign.CENTER;

                wordTf.setTextFormat(myFormat);
                wordTf.autoSize=TextFieldAutoSize.CENTER;
                addChild(wordTf);

Upvotes: 0

Views: 776

Answers (1)

DanielB
DanielB

Reputation: 20230

you are setting the width explicit with wordTf.width=partsWidth;. this will override the autosize option. I would use the following code.

var container:Sprite = new Sprite();

var myFormat:TextFormat = new TextFormat();
    myFormat.size = 16;
    myFormat.align = TextFormatAlign.CENTER;

for each( var thispart:String in parts ) 
{
    var wordTf = new TextField();
    wordTf.defaultTextFormat = myFormat;
    wordTf.name = thispart;
    wordTf.text = thispart;
    wordTf.height=partsHeight;
    wordTf.background=true;
    wordTf.backgroundColor = 0xe3e3e3;
    wordTf.border = true;
    wordTf.width = wordTf.textWidth + 4;
    wordTf.y=150;
    wordTf.x = container.width;
    container.addChild(wordTf);
}

container.x = (stage.stageWidth - container.width) / 2;
addChild(container);

add your words to a separate sprite, and after all words added, add this sprite to the stage and center it.

The line

wordTf.width = wordTf.textWidth + 4;

is the important one. After setting the text, flash can calculate the width of the text. now set this text width (+4 is a fixed padding around the text in a text field you can't modify) as width of your textfield.

Upvotes: 1

Related Questions