Search code examples
javaandroidimagetexturessprite

Sprite image appears stretched and quality is poor, can't get in correct position GDXLib


I am quite new to programming so bear with me here...

I am making a 2d basic game just to practice programming in android studio and can't get my sprite to the correct position on the screen. Also when I draw the sprite it appears stretched and the quality is very poor. Any help is appreciated!

public class MyGdxGame extends ApplicationAdapter {
    SpriteBatch batch;
    Texture background;
    Texture ball;

    @Override
    public void create () {
        batch = new SpriteBatch();
        background = new Texture("gamebackground.png");
        ball = new Texture("ball2.png");
    }

    @Override
    public void render () {

        batch.begin();
        batch.draw(background, 0,0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        batch.draw(ball, 0,0, Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2);
        batch.end();
    }

Solution

  • You need to keep the original width/height ratio:

    instead of scaling it to half the screen size, define your scaling like that:

    float scaleFactor = 2.0f;
    batch.draw(ball, 0,0, ball.getWidth()*scaleFactor, ball.getHeight*scaleFactor);
    

    If your image is "blurry", and you want the individual pixels to stay crisp, try loading the texture like that:

    ball = new Texture("ball2.png");
    ball.setFilter(TextureFilter.Nearest, TextureFilter.Nearest);
    

    This prevents (default) linear interpolation when scaling the texture.