0
votes

I am trying to draw a frame with two textures within Libgdx. My texture is just a white square that i scale and draw with SpriteBatch to the screen. The color is set with batch.setColor(). Now I want to draw a black rectangle and a smaller opaque rectangle in the middle, so it looks like a frame.

batch.begin();
batch.setColor(new Color(0,0,0,1)); //Black
batch.draw(rectangle, 0,0,100,100);
batch.setColor(new Color(0,0,0,0)); //Transparent
batch.draw(rectangle, 25,25,50,50);
batch.end();

I am using this blend function:
Gdx.gl.glBlendFunc(GL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_SRC_COLOR); the problem now is when i draw this it just shows the black rectangle cause the transparent rectangle is drawn on top of it. I want to draw it that I can see through the second rectangle the stuff I drawed before so it acts like a frame. My question is: How can i accomplish this?

Example Background

How it should look

How it looks

1

1 Answers

0
votes

First of all, you should not create new instances of Color in your render() method, since it's called every frame it will lead to a memory leak. Create colors in create() for example. And for black color you could use Color.BLACK instead of creating your own instance.

Back to your question. You can simply just use TextureRegion class. Here is a sample code:

public class MyGdxGame extends ApplicationAdapter {

    SpriteBatch batch;
    Texture whiteRectangle;
    TextureRegion backgroundRegion;

    @Override
    public void create() {
        //initializing batch, whiteTexture, etc...

        //background, the one with a turtle from you example
        Texture backgroundTexture = ...;

        backgroundRegion = new TextureRegion(backgroundTexture);
        //to set a region (part of the texture you want to draw),
        //you can use normalized coordinates (from 0 to 1), or absolute values in pixels
        backgroundRegion.setRegion(0.25f, 0.25f, 0.75f, 0.75f);
    }

    @Override
    public void render() {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        batch.begin();

        //black background
        batch.setColor(Color.BLACK);
        batch.draw(whiteRectangle, 0, 0, 100, 100);

        //on top of that background draw the backgroundRegion
        batch.setColor(Color.WHITE);
        batch.draw(backgroundRegion, 25,25,50,50);

        batch.end();
    }

}