简体   繁体   English

BufferedImage填充具有透明像素的矩形

[英]BufferedImage fill rectangle with transparent pixels

I have a BufferedImage and I am trying to fill a rectangle with transparent pixels. 我有一个BufferedImage,我试图用透明像素填充一个矩形。 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: 使用AlphaComposite ,您至少有两个选择:

  1. Either, use AlphaComposite.CLEAR as suggested, and just fill a rectangle in any color, and the result will be a completely transparent rectangle: 要么按照建议使用AlphaComposite.CLEAR ,然后以任何颜色填充矩形,结果将是一个完全透明的矩形:

     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. 或者,您可以使用AlphaComposite.SRC ,并以透明(或半透明)的颜色绘画。 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. PS :(如Josh在链接的答案中所述),如果您打算使用相同的Graphics2D对象进行更多绘制,请不要忘记在完成后将合成重置为默认的AlphaComposite.SrcOver

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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