Modifying transparency of Texture in LibGDX

6.2k views Asked by At

I want to have a foreground texture overlayed on a background texture. Besides these two textures, I also have a mask that indicates which parts of the foreground should be transparent. This is what I tried:

// Initially, the mask should have an alpha of 1
Pixmap mask = new Pixmap(128, 128, Pixmap.Format.Alpha);

// Cut a rectangle of alpha value 0
mask.setColor(new Color(0f, 0f, 0f, 0f));
mask.fillRectangle(0, 0, 32, 32);

// Load the foreground. The foreground should the same alpha values
// as the mask. If the mask has an alpha value of 1, then the foreground is
// visible. If the mask is 0, then the foreground is invisible.
Pixmap fg = new Pixmap(Gdx.files.internal("foreground.png"));
fg.drawPixmap(mask, fg.getWidth(), fg.getHeight());
Texture foreground = new Texture(fg);

Texture background = new Texture("background.png");

Needless to say, the results aren't what I want them to be. What should I change so that the background is visible wherever the mask has an alpha value of 0, and the foreground is visible wherever the mask has an alpha value of 1.

1

There are 1 answers

0
noone On BEST ANSWER

I think the problem here is blending. Pixmap.setBlending() is set to SourceOver by default. That means drawing a rectangle of alpha 0 results in no change at all, since you draw an invisible rectangle. Try setting it to Pixmap.Blending.None to really cut out the rectangle.

// Initially, the mask should have an alpha of 1
Pixmap mask = new Pixmap(128, 128, Pixmap.Format.Alpha);

// Cut a rectangle of alpha value 0
mask.setBlending(Pixmap.Blending.None);
mask.setColor(new Color(0f, 0f, 0f, 0f));
mask.fillRectangle(0, 0, 32, 32);

Pixmap fg = new Pixmap(Gdx.files.internal("foreground.png"));
fg.drawPixmap(mask, fg.getWidth(), fg.getHeight());
mask.setBlending(Pixmap.Blending.SourceOver);

Texture foreground = new Texture(fg);
Texture background = new Texture("background.png");

Actually you don't even need to create a mask, but you could directly "cut out" the rectangle on the foreground pixmap.