[英]BufferedImage fill rectangle with transparent pixels
我有一个BufferedImage,我试图用透明像素填充一个矩形。 问题是,透明像素没有替换原始像素,而是放在顶部而无所事事。 如何完全消除原始像素? 该代码对于任何其他不透明颜色均适用。
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;
}
使用AlphaComposite
,您至少有两个选择:
要么按照建议使用AlphaComposite.CLEAR
,然后以任何颜色填充矩形,结果将是一个完全透明的矩形:
Graphics2D g = ...; g.setComposite(AlphaComposite.Clear); g.fillRect(x, y, w, h);
或者,您可以使用AlphaComposite.SRC
,并以透明(或半透明)的颜色绘画。 这将替换目标处的任何颜色/透明度,结果将是具有指定颜色的矩形:
Graphics2D g = ...; g.setComposite(AlphaComposite.Src); g.setColor(new Color(0x00000000, true); g.fillRect(x, y, w, h);
如果您只想删除目的地的内容,第一种方法可能会更快,更容易。 第二个更灵活,因为它允许用半透明甚至梯度或其他图像替换区域。
PS :(如Josh在链接的答案中所述),如果您打算使用相同的Graphics2D
对象进行更多绘制,请不要忘记在完成后将合成重置为默认的AlphaComposite.SrcOver
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.