简体   繁体   中英

Full screen background regardless of screen size and keep image aspect ratio

I have a 540x720 background image.

I need to show it in full screen regardless of screen size and resolution (My game will run on desktop and on Android) and regardless of portrait/landscape mode.

I want to keep the aspect ratio of the image, if necessary by cropping the image.

I have already tried ScreenViewport and ExtendViewport but when resizing the window, the background is no longer full screen (for example if the window becomes horizontal) and letter-boxing occurs (showing white side bars).

public class MainMenuScreen implements Screen, InputProcessor {
    final MyGame game;
    
    TextureRegionDrawable textureRegionDrawableBackground = new TextureRegionDrawable(new TextureRegion(new Texture(game.backgroundFileName)));
    
    Stage stageBackground = new Stage(new ScreenViewport());
    // Stage stageBackground = new Stage(new ExtendViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight())));
    
    Image image = new Image(textureRegionDrawableBackground);
    image.setPosition(0, 0);
    image.setHeight(Gdx.graphics.getHeight());
    // makes the background as tall as the screen while maintaining its aspect ratio
    image.setWidth(Gdx.graphics.getHeight() * textureRegionDrawableBackground.getRegion().getRegionWidth() / textureRegionDrawableBackground.getRegion().getRegionHeight());
    stageBackground.addActor(image);
}

public void render(float delta) {
    stageBackground.getViewport().apply();
    stageBackground.draw();
}

public void resize(int width, int height) {
    stageBackground.getViewport().update(width, height, true);
}

How to achieve that?

Thanks

Use FillViewport which will maintain aspect ratio and be full screen by cropping part of the image.

See here https://gamefromscratch.com/libgdx-tutorial-part-17-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