我试图将工具栏按钮粘贴到屏幕的右上角,但每当我调整窗口大小时,按钮都会保持在相同的绝对位置(相对于左下角)。
调整大小之前:
调整大小后:
这是生成 UI 按钮的方法(当前仅在 Screen 的构造函数中调用):
private void generateUiToolbar(){
// Toolbar Table
Table table = new Table();
table.setFillParent(true);
table.top();
table.right();
// Menu button
table.row();
Texture myTexture = new Texture(Gdx.files.internal("ui/stamp.png"));
TextureRegion myTextureRegion = new TextureRegion(myTexture);
TextureRegionDrawable myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
ImageButton menuButton = new ImageButton(myTexRegionDrawable);
menuButton.addListener( new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
stage.clear();
generateUiMenu();
}
});
table.add(menuButton).size(60,60).padTop(10).padRight(10);
stage.addActor(table);
}
这是 resize() 方法:
public void resize(int width, int height) {
stage.getViewport().update(width, height, true);
stage.getCamera().viewportWidth = width;
stage.getCamera().viewportHeight = height;
stage.getCamera().position.set(stage.getCamera().viewportWidth / 2, stage.getCamera().viewportHeight / 2, 0);
stage.getCamera().update();
}
变量 stage 在构造函数中通过 stage = new Stage();
出于某种原因 stage.getViewport().update(width, height, true);
不执行任何操作。当我在调整大小后打印 stage.getWidth() 时,它将返回相同的数字。一般来说,更新按钮或 Actor 位置的好方法是什么?简单地清理舞台并再次生成 UI 对我来说不起作用,因为有时当您调整大小时,当前会显示不同的 Actor 。如果我遗漏了任何信息,请告诉我。
编辑1:
如答案中所述添加了 table.setFillParent(true);
,但这也没有解决问题。
编辑2:
阅读答案和评论后,我删除了 stage.getCamera() 操作,但我仍然没有得到正确的结果。这就是当我仅使用代码行 stage.getViewport().update(width, height, true);
调整大小时发生的情况:
最佳答案
我认为你误解了Viewport的用法。 在调整大小方法中,您执行以下操作:
stage.getViewport().update(width, height, true);
stage.getCamera().viewportWidth = width;
stage.getCamera().viewportHeight = height;
stage.getCamera().position.set(stage.getCamera().viewportWidth / 2, stage.getCamera().viewportHeight / 2, 0);
stage.getCamera().update();
但是 stage.getViewport().update(width, height, true);
已经完成了您在接下来的四行中所做的事情。
viewport.update(width, height)
设置相机的新宽度和高度并更新相机。所以:
viewport.update(width, height)
is equal to
camera.viewportWidth = width;
camera.viewportHeight = height;
camera.update();
唯一的区别是视口(viewport)的长宽比取决于您使用的视口(viewport)。
第三个参数:stage.getViewport().update(width, height, true);
是一个 boolean 值,表示相机是否应该居中。因此,如果第三个参数为 true,视口(viewport)将执行以下操作:
camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0);
在您的调整大小方法中,您覆盖了视口(viewport)的工作,因为使用 viewport.update(width, height, true)
您已经完成了所有调整大小,并且不需要其他四个行。
在调整大小方法中这就足够了:
public void resize(int width, int height) {
stage.getViewport().update(width, height, true);
}
您可以阅读此内容以更好地了解视口(viewport):How Camera works in Libgdx and together with Viewport
关于java - LibGDX 调整窗口大小后如何更新 Actor 位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57129349/