Drawing a gradient in Libgdx

≡放荡痞女 提交于 2019-11-30 11:20:09

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.

Fran Marzoa

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.

There are some further details worth bearing in mind before comitting to ShapeRenderer. I for one will be sticking with stretching and tinting Texture.

private Color topCol = new Color(0xd0000000);
private Color btmCol = new Color(0xd0000000);

@Override
public void render(float delta) {
    ...
    batch.end(); //Must end your "regular" batch first.
    myRect.setColor(Color.YELLOW);  // Must be called, I don't see yellow, but nice to know.
    myRect.begin(ShapeRenderer.ShapeType.Filled); //Everyone else was saying call `set`.
    //Exception informed me I needed `begin`. Adding `set` after was a NOP.
    myRect.rect(
            10, 400,
            //WORLD_H - 300,  // WORLD_H assumed 1920. But ShapeRenderer uses actual pixels.
            420,
            300,
            btmCol, btmCol, topCol, topCol
    );
    myRect.end();

I was hoping to change transparency dynamically as player health declines. The btmCol and topCol had no effect on transparency, hence I'll stick to Textures. Translating pixel space is no biggie, but this is much more than the proferred single or double line above.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!