BufferedImage fill rectangle with transparent pixels

白昼怎懂夜的黑 提交于 2019-12-31 05:05:07

问题


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;
}

回答1:


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.



来源:https://stackoverflow.com/questions/43882050/bufferedimage-fill-rectangle-with-transparent-pixels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!