Question

So I'm making a simple pause function in my game, and I want to have a grey transparent background, the problem is, the rectangle keeps overlapping and is just causing a fade out look. I've tried g2.dispose, and it works, but I can't draw anything else over that.

I have my render method, which is being called 60 times a second. (I issume the rectangle is being drawn 60 times a second)

    public void render(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setColor(new Color(0, 0, 0, 50));
    g2.fillRect(0, 0, RPG.getWidth(), RPG.getHeight());
    g2.drawImage(paused, 0, 0, null);
}

Thanks!

Was it helpful?

Solution

Edit: I feel like an idiot... I just had to draw my ingame screen underneath that!

OTHER TIPS

If I understand correctly what you mean by "causing a fade out look" (although I'm not sure I do), you want to fill a background with a transparent color without blending the new transparent color with pixels that are already present. You can do this by setting the composite mode to "source":

g2.setComposite(AlphaComposite.Src);

You can set it back to the default "source over destination" rule to return to normal drawing afterwards by doing:

g2.setComposite(AlphaComposite.SrcOver);

Edit: Or perhaps you do want to blend the transparent color, but with the rest of the game graphics and not with itself? In that case, just make sure that you're redrawing the game background each time you draw the transparency over the top, although I'd suggest pausing the 60fps refresh during game pause if nothing on the screen is changing, just to avoid wasting CPU/battery.

Consider trying to create a copy of the Graphics context first and then disposing of it when your finished...

public void render(Graphics g) {
    Graphics2D g2 = (Graphics2D) g.create();
    g2.setColor(new Color(0, 0, 0, 50));
    g2.fillRect(0, 0, RPG.getWidth(), RPG.getHeight());
    g2.drawImage(paused, 0, 0, null);
    g2.dispose();
}

This way, the changes to the Graphics state remain isolated between the create and dispose calls and don't affect anything else painted after it

Also, remember, unless you are clearing what was previously painted to the Graphics context, it will accumulate on repeated calls.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top