Java: Filling a BufferedImage with transparent pixels

后端 未结 6 715
无人共我
无人共我 2020-11-30 06:46

I have an off-screen BufferedImage, constructed with the type BufferedImage.TYPE_INT_ARGB. It can contain anything, and I\'m looking for a way to (fairly effic

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 07:33

    For the sake of completeness, here is a working, testing, and fast function that is cross-platform compliant.

      static public BufferedImage createTransparentBufferedImage(int width, int height) {
         // BufferedImage is actually already transparent on my system, but that isn't
         // guaranteed across platforms.
         BufferedImage bufferedImage = new BufferedImage(width, height, 
                            BufferedImage.TYPE_INT_ARGB);
         Graphics2D graphics = bufferedImage.createGraphics();
    
         // To be sure, we use clearRect, which will (unlike fillRect) totally replace
         // the current pixels with the desired color, even if it's fully transparent.
         graphics.setBackground(new Color(0, true));
         graphics.clearRect(0, 0, width, height);
         graphics.dispose();
    
         return bufferedImage;
      }
    

提交回复
热议问题