BufferedImage fill rectangle with transparent pixels

北战南征 提交于 2019-12-02 04:22:42

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.

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