user3240131
user3240131

Reputation: 207

How to accurately center a TextField in as3?

I am trying to center a text field on a sprite. I have read answers regarding this issue. Supposedly, the solution is to proceed like this :

textField.x = sprite.width/2 - textField.textWidth/2;
textField.y = sprite.height/2 - textField.textHeight/2;

I have tried it and it "kind of" works but the result is really inaccurate in my opinion. Here is what I get with the following code :

bad centering

package
{
    import flash.display.Shape;
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;

    public class MainTest extends Sprite
    {
        public function MainTest()
        {   
            var sprite:Sprite = new Sprite();
            var background:Shape = new Shape();
            background.graphics.beginFill(0xAAAAAA);
            background.graphics.drawRect(0, 0, 50, 20);
            background.graphics.endFill();
            sprite.addChild(background);
            var tf:TextField = new TextField();
            tf.text = "Test";
            tf.autoSize = TextFieldAutoSize.LEFT;
            sprite.addChild(tf);
            stage.addChild(sprite);
            tf.x = sprite.width/2 - tf.textWidth/2;
            tf.y = sprite.height/2 - tf.textHeight/2;
            sprite.x = stage.stageWidth / 2 - sprite.width / 2;
            sprite.y = stage.stageHeight / 2 - sprite.height / 2;
        }
    }

}

The gap on the left is too big and the this is definitely not vertically centered! Do you get the same result? Any idea of what I am doing wrong?

Upvotes: 0

Views: 1869

Answers (2)

divillysausages
divillysausages

Reputation: 8053

Use tf.width and tf.height rather than textWidth and textHeight. The latter don't take into account the padding/margins etc.

This images from TextLineMetrics shows the difference:

TextLineMetrics showing the difference between textWidth/textHeight and width/height

Upvotes: 1

h2ooooooo
h2ooooooo

Reputation: 39550

Have you considered not using TextFieldAutoSize and instead simply use the in built align methods built into TextFormat?

var textFormat:TextFormat = new TextFormat();
textFormat.align = "center";

tf.setTextFormat(textFormat);

Alternatively, have you checked out TextFieldAutoSize.CENTER?

Upvotes: 0

Related Questions