简体   繁体   中英

LibGdx - How can I resize my game window while keeping the aspect ratio?

Right now, I'm trying to code something that makes it where when the window is resized with the mouse, it will stay at a 16:9 aspect ratio. I'd like to have the code for this inside of my desktop launcher (I'm only compiling to desktop) but I'm also ok with doing it in my game file with public void resize() if I have to. I'm using Libgdx 3 so I can't use stuff like cfg.height but I'm curious if I can do it using config.setWindowSizeLimits() and just change the boundaries when necessary. If I'm missing something and there actually is a way to get the window's dimensions inside of desktop launcher that would be very good to know.

You can use a FitViewport . This will not fix the ratio of the window itself, but it keeps the aspect ratio by scaling the world up to fit the screen, adding black bars (letterboxing) for the remaining space .

You can use it like this:

public void initializeCameraAndViewport() {
    camera = new OrthographicCamera();
    viewport = new FitViewport(SCENE_WIDTH, SCENE_HEIGHT, camera);
}

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

It will make the screen look like this:

适合视口

See the libgdx wiki for a more detailed description of viewports.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM