简体   繁体   中英

BufferedImage fill rectangle with transparent pixels

I have a BufferedImage and I am trying to fill a rectangle with transparent pixels. The problem is, instead of replacing the original pixels, the transparent pixels just go on top and do nothing. How can I get rid of the original pixel completely? The code works fine for any other opaque colors.

public static BufferedImage[] slice(BufferedImage img, int slices) {
    BufferedImage[] ret = new BufferedImage[slices];

    for (int i = 0; i < slices; i++) {
        ret[i] = copyImage(img);

        Graphics2D g2d = ret[i].createGraphics();

        g2d.setColor(new Color(255, 255, 255, 0));

        for(int j = i; j < img.getHeight(); j += slices)
            g2d.fill(new Rectangle(0, j, img.getWidth(), slices - 1));

        g2d.dispose();
    }

    return ret;
}

public static BufferedImage copyImage(BufferedImage source){
    BufferedImage b = new BufferedImage(source.getWidth(), source.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics g = b.getGraphics();
    g.drawImage(source, 0, 0, null);
    g.dispose();
    return b;
}

Using AlphaComposite , you have at least two options:

  1. Either, use AlphaComposite.CLEAR as suggested, and just fill a rectangle in any color, and the result will be a completely transparent rectangle:

     Graphics2D g = ...; g.setComposite(AlphaComposite.Clear); g.fillRect(x, y, w, h); 
  2. Or, you can use AlphaComposite.SRC , and paint in a transparent (or semi-transparent if you like) color. This will replace whatever color/transparency that is at the destination, and the result will be a rectangle with exactly the color specified:

     Graphics2D g = ...; g.setComposite(AlphaComposite.Src); g.setColor(new Color(0x00000000, true); g.fillRect(x, y, w, h); 

The first approach is probably faster and easier if you want to just erase what is at the destination. The second is more flexible, as it allows replacing areas with semi-transparency or even gradients or other images.


PS: (As Josh says in the linked answer) Don't forget to reset the composite after you're done, to the default AlphaComposite.SrcOver , if you plan to do more painting using the same Graphics2D object.

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