如何准确地将TextField置于as3中心?

时间:2014-04-09 09:21:02

标签: actionscript-3

我试图将一个文本字段居中在精灵上。 我已经阅读了有关此问题的答案。据说,解决方案是这样进行的:

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

我已经尝试了它并且“有点”有效,但结果在我看来真的不准确。 以下是我用以下代码获得的内容:

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;
        }
    }

}

左边的间隙太大,这绝对不是垂直居中的! 你得到相同的结果吗?我知道我做错了什么?

2 个答案:

答案 0 :(得分:1)

使用tf.widthtf.height而不是textWidthtextHeight。后者不考虑填充/边距等。

来自TextLineMetrics的图片显示了差异:

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

答案 1 :(得分:0)

您是否使用TextFieldAutoSize考虑,而只是使用内置于TextFormat的内置对齐方法?

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

tf.setTextFormat(textFormat);

或者,您是否已查看TextFieldAutoSize.CENTER