Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing a gradient in Libgdx

Ok I have this code

@Override
public void render() {
    // do not update game world when paused
    if (!paused) {
        // Update game world by the time that has passed
        // since last render frame
        worldController.update(Gdx.graphics.getDeltaTime());
    }
    // Sets the clear screen color to: Cornflower Blue
    Gdx.gl.glClearColor(0x64/255.0f, 0x95/255.0f, 0xed/255.0f,
            0xff/255.0f);
    // Clears the screen
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
    // Render game world to screen
    worldRenderer.render();
}

And it draws a light blue background onto the screen. I am attempting to create a gradient that goes from a dark blue at the top, to a light blue towards the bottom. Is there a simple way to do this? I'm new to Libgdx, and OpenGL so i'm trying to learn from a book but I can't seem to find the answer to this one. I've heard of drawing a big square and having the vertices different colors, but I'm unsure of how to do this.

like image 547
JonFavale Avatar asked Jan 02 '14 18:01

JonFavale


2 Answers

In libGDX, the ShapeRenderer object contains a drawRect() method that takes arguments for its position and size as well as four colors. Those colors are converted to a 4-corners gradient. If you want a vertical gradient, just make the top corners one color and the bottom corners another color. Something like this:

shapeRenderer.filledRect(x, y, width, height, lightBlue, lightBlue, darkBlue, darkBlue);

From the API for ShapeRenderer:

The 4 color parameters specify the color for the bottom left, bottom right, top right and top left corner of the rectangle, allowing you to create gradients.

like image 124
Kevin Workman Avatar answered Oct 13 '22 05:10

Kevin Workman


It seems ShapeRenderer.filledRect method has been removed in late libGDX versions. Now the way to do this is as follows:

shapeRenderer.set(ShapeRenderer.ShapeType.Filled);
shapeRenderer.rect(
        x,
        y,
        width,
        height,
        Color.DARK_GRAY,
        Color.DARK_GRAY,
        Color.LIGHT_GRAY,
        Color.LIGHT_GRAY
);

The parameters for rect method work in the same way as those in filledRect used to do, like in Kevin Workman answer.

like image 35
Fran Marzoa Avatar answered Oct 13 '22 06:10

Fran Marzoa