user236520
user236520

Reputation:

Why is my sprite not being drawn correctly (libgdx)?

I have a 1024x1024 pixel image in a jpg file. I am trying to render it onscreen with libgdx such that it fills the whole screen. At this stage I am not concerned with the image preserving its aspect ratio.

In my show() method I parse the jpg and initialize the sprite thus:

mWidth = Gdx.graphics.getWidth();
mHeight = Gdx.graphics.getHeight();

mCamera = new OrthographicCamera(1, mHeight/mWidth);
mBatch = new SpriteBatch();

mTexture = new Texture(Gdx.files.internal("my jpg file"));

mTexture.setFilter(TextureFilter.Linear, TextureFilter.Linear);

TextureRegion region = new TextureRegion(mTexture);

mSprite = new Sprite(region);
mSprite.setSize(0.99f, 0.99f);
mSprite.setOrigin(mSprite.getWidth()/2, mSprite.getHeight()/2);
mSprite.setPosition(-mSprite.getWidth()/2, -mSprite.getHeight()/2);

and in the render() method, I draw the sprite thus

Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

mBatch.setProjectionMatrix(mCamera.combined);
mBatch.begin();
mSprite.draw(mBatch);
mBatch.end();

but all that is actually rendered is a blank white screen. What am I doing wrong?

Upvotes: 1

Views: 447

Answers (2)

user3312130
user3312130

Reputation: 178

To the best of my knowledge, mSprite.setSize(0.99f, 0.99f); sets the pixel width and height of a sprite whereas setScale scales the sprite's dimensions. Setting setSize to something larger such as 256 x 256 should make your sprite visible and setting it to the resolution of the screen should make it fill the screen if all goes well. The examples linked by Tanmay Patil are great so look into them if you're having trouble.

Upvotes: 1

Tanmay Patil
Tanmay Patil

Reputation: 7057

  1. You should use

    mCamera = new OrthographicCamera(mWidth, mHeight);
    

    in stead of

    mCamera = new OrthographicCamera(1, mHeight/mWidth);
    

    in most cases, unless you want to scale things in a different way.

  2. Check if your code has actually found and read the file successfully. If not, check things like full path, file extension, intermediate spaces etc.

  3. In resize method, try adding following

    mBatch.getProjectionMatrix().setToOrtho2D(0, 0, mWidth, mHeight);
    
  4. If it isn't working even then, I'd recommend falling back to the working libgdx logo sprite being drawn when you create a new project with setup ui. Change things slowly from there.

For reference, use https://code.google.com/p/libgdx-users/wiki/Sprites

Good luck.

Upvotes: 1

Related Questions