全屏背景与屏幕大小无关并保持图像纵横比

时间:2021-07-15 09:38:36

标签: java android graphics libgdx fullscreen

我有一张 540x720 的背景图片。

无论屏幕大小和分辨率如何(我的游戏将在桌面和 Android 上运行),也不管纵向/横向模式如何,我都需要全屏显示。

如果需要,我想通过裁剪图像来保持图像的纵横比。

我已经尝试过 ScreenViewport 和 ExtendViewport,但是在调整窗口大小时,背景不再是全屏(例如,如果窗口变为水平)并且出现信箱(显示白色边栏)。

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);
}

如何实现?

谢谢

1 个答案:

答案 0 :(得分:0)

使用 FillViewport 将通过裁剪图像的一部分来保持纵横比和全屏。

看这里 https://gamefromscratch.com/libgdx-tutorial-part-17-viewports/