简体   繁体   中英

Add a transparent gradient to a JPanel?

I'm drawing a couple of shapes on a JPanel using the paintComponent() method. The final touch is to add a transparent white gradient towards the top.

I have this:

1

and I want to get something like this:

2

I've tried to use the GradientPaint method, but it doesn't seem to work properly for me at all. When I call g.setPaint(new GradientPaint(...)) , it can't seem to draw over the existing pixels at all.

If anyone would like to see what I'm doing, an SSCCE of the code is available at this Pastebin .

It seems to produce an effect if these are added as the last lines of paintComponent(Graphics) .

// now we have set a paint, DO SOMETHING WITH IT!
g.fillRect(0, 0, getWidth(), getHeight());

Result

在此处输入图片说明

Try applying a AlphaComposite before painting the gradient

g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));

The other thing you could try is to use a color with an alpha value within the gradient...

LinearGradientPaint lgp = new LinearGradientPaint(
    startPoint, endPoint, new float[]{...}, 
    new Color[] {
        new Color(255, 255, 255, 0),
        new Color(255, 255, 255, 128),
        new Color(255, 255, 255, 0),
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM