How to draw on just a portion of the screen with SpriteBatch in libgdx?

前端 未结 4 1573
-上瘾入骨i
-上瘾入骨i 2021-01-23 07:53

When I do this:

SpriteBatch spriteBatch = new SpriteBatch();
spriteBatch.setProjectionMatrix(new Matrix4().setToOrtho(         


        
相关标签:
4条回答
  • 2021-01-23 08:08

    You're going to want to use the ScissorStack. Effectively, you define a rectangle that you want to draw in. All drawing will be in the rectangle that you defined.

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

    This will limit rendering to within the bounds of the rectangle "clipBounds". It is also possible push multiple rectangles. Only the pixels of the sprites that are within all of the rectangles will be rendered.

    From http://code.google.com/p/libgdx/wiki/GraphicsScissors

    0 讨论(0)
  • 2021-01-23 08:11

    You could either

    • double the viewport width of the SpriteBatch
    • use a Sprite and set its width scale to 0.5f (be careful about the origin) and use its draw(SpriteBatch) method to draw it.
    0 讨论(0)
  • 2021-01-23 08:23

    Perhaps I am misunderstanding the question, but could you not just double the viewport width, setting it to 640 instead of 320?

    SpriteBatch spriteBatch = new SpriteBatch;
    spriteBatch.setProjectionMatrix(new Matrix4().setToOrtho(0, 640, 0, 240, -1, 1));
    spriteBatch.begin();
    spriteBatch.draw(textureRegion, 0, 0);
    spriteBatch.end();
    
    0 讨论(0)
  • 2021-01-23 08:26

    Before rendering the batch, you can set the viewport to draw on a specific screen area. The important line is:

    Gdx.gl.glViewport(x, 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 want to see only a part of that original viewport, we need to change both the size and the starting position. To draw only on the left half of the screen, use:

    x = 0;
    y = 0;
    w = Gdx.graphics.getWidth()/2;
    h = Gdx.graphics.getWidth();
    

    I found the solution here and originally answered this question to a slightly more complicated problem, but the technique is the same.

    To focus on any different portion of the viewport, simply choose x, y, w, and h accordingly. If you're going to do any more rendering in the normal fashion, make sure to reset the viewport with the original x, y, w, and h values.

    0 讨论(0)
提交回复
热议问题