How to use ExtendViewport in libgdx game screen?


ExtendViewport :
The ExtendViewport keeps the world aspect ratio without black bars by extending the world in one direction. The world is first scaled to fit within the viewport, then the shorter dimension is lengthened to fill the viewport.

public class TestScreen implements Screen {
    private OrthographicCamera camera;
    private ExtendViewport viewport;
    private SpriteBatch batch;
    private Sprite dotSprite;


    public TestScreen(GameContext context) {
        this.batch = context.batch;

        camera = new OrthographicCamera();
        viewport = new ExtendViewport(720,1280, camera);

        dotSprite = new Sprite(new Texture("dots/dot.png"));

    }

    @Override
    public void show() {

    }

    @Override
    public void render(float delta) {

        camera.update();
        batch.setProjectionMatrix(camera.combined);


        Gdx.gl.glClearColor(1f, 0f, 0f, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT
                | GL20.GL_DEPTH_BUFFER_BIT
                | (Gdx.graphics.getBufferFormat().coverageSampling ?
                GL20.GL_COVERAGE_BUFFER_BIT_NV : 0));


        dotSprite.setPosition(camera.viewportWidth - dotSprite.getWidth(), camera.viewportHeight - dotSprite.getHeight());

        batch.begin();
        dotSprite.draw(batch);
        batch.end();
    }

    @Override
    public void resize(int width, int height) {
        viewport.update(width, height);
        camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0);
        camera.update();
    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void hide() {

    }

    @Override
    public void dispose() {

    }
}



Comments