Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing a transparent shape in libGDX as an Actor?

Tags:

android

libgdx

I'm trying to draw a simple rect on the screen in a class and using it as an actor.

But whatever I do, it seems that there is no option to draw it transparent. Does anyone know how to do this? Thanks in advance!

public class AreaColorRect extends Actor {

    public float opacity = 0.0f;
    private Color shapeFillColor = new Color();
    public Rectangle area;
    public ShapeRenderer shapeRen;

    public AreaColorRect(float x, float y, float w, float h) {
        shapeRen = new ShapeRenderer();
        this.area = new Rectangle(x, y, w, h);
    }


    @Override
    public void draw(SpriteBatch batch, float parentAlpha) {
        shapeRen.begin(ShapeType.Filled);
        shapeRen.setColor(new Color(shapeFillColor.r, shapeFillColor.g, shapeFillColor.b,
            0.0f));
        shapeRen.rect(area.x, area.y, area.width, area.height);
        shapeRen.end();
    }

    public void setShapeFillColor(float r, float g, float b) {
        this.shapeFillColor = new Color(r, g, b, 1);
    }

}
like image 830
EchtFettigerKeks Avatar asked Jan 14 '23 10:01

EchtFettigerKeks


2 Answers

You're mixing contexts. End your SpriteBatch before starting the ShapeRenderer. See libgdx - ShapeRenderer in Group.draw renders in wrong colour. This might not be the problem, though.

You also need to turn on blending. You can just do this once globally, or enable it as necessary (and disable it). It should be enabled by the SpriteBatch context, but I don't think its enabled for the ShapeRenderer.

Gdx.graphics.getGL10().glEnable(GL10.GL_BLEND); // Or GL20

The order you render your background and Actors also makes a difference for transparency.

Finally, you've set the opacity to 0, so the object will be completely invisible. That generally doesn't do anything at all. (I assume you're just trying to get a change from the current 100% visible?)

like image 171
P.T. Avatar answered Jan 21 '23 04:01

P.T.


Sorry for digging this up. Since you are tagging Android, though, I thought I would just chip in my experiences. I recently spent almost 4 hours on a problem, where alpha blending just wasn't working, as it isn't for you.

Turned out that libgdx' AndroidApplicationConfiguration uses 0 bit for alpha channel as default. If this is the case for you, too, it might be worth changing that to something more sensible before you initialize() your app.

like image 36
suluke Avatar answered Jan 21 '23 04:01

suluke