libgdx scene2d返回错误的标签高度

时间:2014-12-18 23:31:31

标签: java libgdx scene2d

我想在屏幕上的一个确切的特定点放置三个文本标签(在这种情况下在顶部以更容易地说明问题)。所以我有:

LabelStyle labelStyle = new LabelStyle(new BitmapFont(), new Color(1,1,1,1));

Label textFullSize = new Label("Line 1 of 4\nLine 2 of 4\nLine 3 of 4\nLine 4 of 4", labelStyle);
textFullSize.setFontScale(1);
textFullSize.setPosition(0, Gdx.graphics.getHeight()-textFullSize.getPrefHeight());
stage.addActor(textFullSize);

Label textHalfSize = new Label("Line small 1 of 4\nLine small 2 of 4\nLine small 3 of 4\nLine small 4 of 4", labelStyle);
textHalfSize.setFontScale(0.5f);
textHalfSize.setPosition(Gdx.graphics.getWidth()*0.15f, Gdx.graphics.getHeight()-textHalfSize.getPrefHeight());
stage.addActor(textHalfSize);       

Label textDoubleSize = new Label("Line large 1 of 4\nLine large 2 of 4\nLine large 3 of 4\nLine large 4 of 4", labelStyle);
textDoubleSize.setFontScale(2);
textDoubleSize.setPosition(Gdx.graphics.getWidth()*0.25f, Gdx.graphics.getHeight()-textDoubleSize.getPrefHeight());
stage.addActor(textDoubleSize);

但这是我得到的: wrong label positioning

为什么会这样?为什么getPrefHeight()不能返回标签的正确高度?如何在没有标签的情况下定位标签?

1 个答案:

答案 0 :(得分:0)

更改标签的比例时,在调用stage.act()之前不会自动调用其新大小。这是为了避免浪费大量计算重新计算所有内容的大小,如果你进行多项影响大小的更改。

但您可以通过调用标签上的layout()强制它更新其大小。然后,当您致电getPrefHeight()时,您将获得正确的价值。例如:

Label textHalfSize = new Label("Line small 1 of 4\nLine small 2 of 4\nLine small 3 of 4\nLine small 4 of 4", labelStyle);
textHalfSize.setFontScale(0.5f);
textHalfSize.layout();
textHalfSize.setPosition(Gdx.graphics.getWidth()*0.15f, Gdx.graphics.getHeight()-textHalfSize.getPrefHeight());
stage.addActor(textHalfSize);  

一般来说,这并不浪费,因为它会在内部将其布局标记为已更新,因此在大多数情况下,它不必在stage.act()中重新计算这些内容。