BufferedImage填充矩形,带有透明像素 [英] BufferedImage fill rectangle with transparent pixels

查看:176
本文介绍了BufferedImage填充矩形,带有透明像素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个BufferedImage,我正在尝试用透明像素填充一个矩形。问题是,透明像素不是替换原始像素,而是放在顶部而不做任何事情。如何完全摆脱原始像素?该代码适用于任何其他不透明的颜色。

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


推荐答案

使用 AlphaComposite ,您至少有两个选择:

Using AlphaComposite, you have at least two options:


  1. 要么使用 AlphaComposite.CLEAR 按照建议,只需填充任何颜色的矩形,结果将是一个完全透明的矩形:

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


  • 或者,您可以使用 AlphaComposite.SRC ,并以透明(或半透明,如果你喜欢)颜色绘画。这将替换目标处的任何颜色/透明度,结果将是一个完全指定颜色的矩形:

  • 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 :(正如Josh在链接答案)如果您打算使用相同的<$ c进行更多绘画,请不要忘记在完成后将复合重置为默认 AlphaComposite.SrcOver $ c> Graphics2D object。

    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.

    这篇关于BufferedImage填充矩形,带有透明像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆