Search code examples
javaactionlibgdxscaling

Scene2d Image won't scale


I am starting to learn libgdx and with it scene2d, but I have been having trouble with my splashScreen. My fade actions work perfectly, but the Image isn't being scaled (even when I add a Scaling to the constructor)...

I have a Texture splashTexture loaded from a png 512x512, of which the real image is 512x256, so I create a TextureRegion. All of this is done in my show method:

@Override
    public void show() {
    super.show(); //sets inputprocessor to stage

    splashTexture = new Texture(SPLASHADR);

    // set the linear texture filter to improve the stretching
    splashTexture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
    splashTextureRegion = new TextureRegion(splashTexture, 0, 0, 512, 256);

}

Then comes the following in my resize method:

@Override
public void resize(int width, int height) {
    stage.clear();
    Drawable splashTextureDrawable = new TextureRegionDrawable(
            splashTextureRegion);

    Image splashImg = new Image(splashTextureDrawable);

    splashImg.getColor().a = 0f;
    splashImg.addAction(Actions.sequence(Actions.fadeIn(0.5f),
            Actions.delay(2f), Actions.fadeOut(0.5f)));

    stage.addActor(splashImg);

}

These are functions in a class SplashScreen which extends an AbstractScreen class (which actually has the render function):

@Override
public void render(float delta) {
    stage.act(delta);

    Gdx.gl.glClearColor(0f, 0f, 0f, 1f);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    stage.draw();
}

Any ideas are welcome, I've been looking through the javadocs for ages and haven't found a solution yet!

Thank you,

bnunamak


Solution

  • Check out stage.setViewport(float width, float height, boolean keepAspectRatio). It sounds like you want the image to fill the screen, so set the stage's viewport width/height to your image's width/height:

    stage.setViewport(512, 256, false);
    

    See the scene2d wiki article for an explanation of the keepAspectRatio parameter:

    setViewport has a parameter named keepAspectRatio which only has an effect when the stage size and viewport size aspect ratio differ. If false, the stage is stretched to fill the viewport, which may distort the aspect ratio. If true, the stage is first scaled to fit the viewport in the longest dimension. Next the shorter dimension is lengthened to fill the viewport, which keeps the aspect ratio from changing.

    If that wasn't exactly what you wanted, the article has a few different examples which should cover what you need.