alanmcknee
alanmcknee

Reputation: 199

Java, android LibGDX - gradient filled circle

Is there a way to fill cricle with a gradient? I've found this option for the rectangle, but no for the circle.

Something like

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

but for the circle.

It would be even better to fill with the gradient only circle's border (to be precise, I need circle with a hole inside - something like a donut. But if there's no option like this, I can draw another circle onto this one).

Image is not an option, It would be a lot of different colors, possibly even changing in time.

Upvotes: 1

Views: 351

Answers (1)

I've been looking a lot into masking since I thought that was the way to go about your question, and good news! I finally have a solution for you, hope it will be useful for you and others. I took a look here Masking Test by mattdesl all credits to him

private ShapeRenderer shapeRenderer;

@Override
public void create() {
    shapeRenderer = new ShapeRenderer();
}

@Override
public void render() {
    //1. clear screen
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    //2. clear our depth buffer with 1.0
    Gdx.gl.glClearDepthf(1f);
    Gdx.gl.glClear(GL20.GL_DEPTH_BUFFER_BIT);

    //3. set the function to LESS
    Gdx.gl.glDepthFunc(GL20.GL_LESS);

    //4. enable depth writing
    Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);

    //5. Enable depth writing, disable RGBA color writing
    Gdx.gl.glDepthMask(true);
    Gdx.gl.glColorMask(false, false, false, false);

    ///////////// Draw mask shape(s)

    //6. render your primitive shapes
    shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);

    shapeRenderer.setColor(1f, 0f, 0f, 0.5f);
    shapeRenderer.circle(50, 50, 50);
    shapeRenderer.setColor(0f, 1f, 0f, 0.5f);

    shapeRenderer.end();

    ///////////// Draw sprite(s) to be masked

    shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
    Gdx.gl.glColorMask(true, true, true, true);
    Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
    Gdx.gl.glDepthFunc(GL20.GL_EQUAL);
    shapeRenderer.set(ShapeRenderer.ShapeType.Filled);
    shapeRenderer.rect(0, 0, 100, 100, Color.RED, Color.RED, Color.BLUE, Color.BLUE);
    shapeRenderer.end();
}

Keep in mind this also works for Sprites, Textures and TextureRegions rendered by a SpriteBatch!

Upvotes: 1

Related Questions