BufferedImage fill rectangle with transparent pixels

后端 未结 1 1700
旧巷少年郎
旧巷少年郎 2021-01-27 01:43

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 t

相关标签:
1条回答
  • 2021-01-27 02:25

    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.

    0 讨论(0)
提交回复
热议问题