[LibGDX]Render portion of a Texture/Sprite

Oddly enough, I couldn’t find a tutorial about this.

I have large background images and I feel it’s a waste to render the whole thing when the window is 800x600.

So I want a function that renders portion of the image, but cant find anything.

I would do the following (for LWJGL):


// image is for example 8000x6000
float width = 8000;
float height = 6000;
// centerX and centerY are floats that symbolize the middle of the screen's coordinates on the Background

GL11.glBegin(GL11.GL_QUADS);
GL11.glTexCoord2f((centerX-400f)/width,(centerY-300f)/height);
GL11.glVertex2f(0,0);
GL11.glTexCoord2f((centerX+400f)/width,(centerY-300f)/height);
GL11.glVertex2f(800,0);
GL11.glTexCoord2f((centerX+400f)/width,(centerY+300f)/height);
GL11.glVertex2f(800,600);
GL11.glTexCoord2f((centerX-400f)/width,(centerY+300f)/height);
GL11.glVertex2f(0,600);
GL11.glEnd();

and then just move the centerX and centerY coordinates

Fustrum culling. Render only what the camera sees.

Our just create a texture region from it if the cam does not move.

I am not talking about culling. And the camera is moving.

Seiya02: I will look into that. Although I dont understand much from LWJGL. Where do I set which texture to render?

You have to bind the right texture to OpenGL with glBindTexture(int textureID).

Create a TextureRegion like Gibbo said. Then, you just adjust the TextureRegion to only draw what the screen is showing. I believe that there may also be some parameters in one of the SpriteBatch#draw methods that allows you to adjust the uv coordinates. I can provide more info if you need once I get access to a computer.

Are you referring to the following method?

spriteBatch.draw(texture, x, y, width, height, u, v, u2, v2);

I tried it but couldnt get it to work. I am not sure how to use it.

And the TextureRegion is not working either. I am guessing you are referring to region.setRegion(x,y,width,height) ?

EDIT: Never mind, got it to work :slight_smile:

Glad you got it working. Which method do you use?

Thanks. I used the spritebatch function in the code block above. I had to google what u,v,u2 and v2 was though.

Rendering a portion of a large image is definitely preferred. Some visual glitches was fixed. And I can imagine releasing stress from the GPU.

Instead of using the sprite batch method, I have to use the functions found in TextureRegion to set the region.

The results are odd. Everything is zoomed and its looks just way off.

Edit: Managed to solve it! For those wondering how:

img.setRegion(u, v, u2, v2);
img.setSize(width, height);
img.setPosition(startX, startY);
img.draw(batch);