Libgdx锁定纵横比到一定范围

时间:2016-03-25 00:43:35

标签: java libgdx window aspect-ratio

是否可以设置最小和最大宽高比? 可以说从1:1到2.5:1。或者至少设置宽度和高度的最小值和最大值?

1 个答案:

答案 0 :(得分:0)

您可以使用FitViewport来保持固定的宽度和高度:

FitViewport viewport = new FitViewport(SCREEN_WIDTH, SCREEN_HEIGHT, camera);

如果您使用Stage绘制所有演员,那么您需要做的就是在舞台上设置视口,如下所示:

stage.setViewport(viewport);

但是,如果您不使用舞台,则需要执行以下操作。如果您使用SpriteBatch直接绘图,则还需要设置Camera

SpriteBatch batch = new SpriteBatch();
OrthographicCamera camera = new OrthographicCamera(SCREEN_WIDTH, SCREEN_HEIGHT);
camera.setToOrtho(true);
//center the camera in the center of the screen
camera.position.set(SCREEN_WIDTH / 2f, SCREEN_HEIGHT / 2f, 0f);
//pass the camera to the third argument of the viewport
FitViewport viewport = new FitViewport(SCREEN_WIDTH, SCREEN_HEIGHT, camera);

然后,您需要在渲染时在CameraSpriteBatch上设置投影矩阵:

@Override
public void render(float deltaTime) {
    camera.update();
    batch.setProjectionMatrix(camera.combined);

    // do all the rendering of textures and stuff

}

每次调整屏幕大小时,您还需要更新视口:

@Override
public void resize(int width, int height) {
    viewport.update(width, height);
}