How to draw only part of the screen using SpriteBatch in libgdx?

When I do this:

SpriteBatch spriteBatch = new SpriteBatch();
spriteBatch.setProjectionMatrix(new Matrix4().setToOrtho(0, 320, 0, 240, -1, 1));
spriteBatch.draw(textureRegion, 0, 0);



will draw textureRegion

in the coordinate system 320-240 that I have specified for the entire screen. Let's say I want to draw with the same coordinate system 320 240 but only on the left half of the screen (which means everything will be scaled down horizontally on the left side, leaving the right half of the screen black), how can I do this?


source to share

4 answers

You will need to use ScissorStack. In fact, you are defining the rectangle you want to draw. The entire drawing will be in the rectangle you specified.

Rectangle scissors = new Rectangle(); 
Rectangle clipBounds = new Rectangle(x,y,w,h);
ScissorStack.calculateScissors(camera, spriteBatch.getTransformMatrix(), clipBounds, scissors); 


This limits rendering to the "clipBounds" rectangle. It is also possible to click multiple rectangles. Only the pixels of the sprites that are in all rectangles will be displayed.




I may not understand the question, but could you just double the width of the viewport by setting it to 640 instead of 320?

SpriteBatch spriteBatch = new SpriteBatch;
spriteBatch.setProjectionMatrix(new Matrix4().setToOrtho(0, 640, 0, 240, -1, 1));
spriteBatch.draw(textureRegion, 0, 0);




You can either

  • double the width of the viewport SpriteBatch

  • use Sprite

    and set its scale width to 0.5f (be careful with the source) and use its method draw(SpriteBatch)

    to draw it.


Before rendering the batch, you can adjust the viewport to a specific area of ​​the screen. Important line:, y, w, h);


The viewport usually starts at x = 0 and y = 0 and extends to the full width and height of the screen. If we only want to see a portion of this original viewport, we need to resize and start position. To draw only on the left half of the screen, use:

x = 0;
y = 0;
w =;
h =;


I found a solution here and originally answered this question for a slightly more complex problem, but the method is the same.

To focus on any other part of the viewport, simply select x, y, w, and h respectively. If you are going to do any rendering normally, make sure to reset the viewport to its original x, y, w, and h values.



All Articles