Clear a transparent BufferedImage as fast as possible

adrian.tarau picture adrian.tarau · Mar 2, 2010 · Viewed 12.1k times · Source

I have a transparent BufferedImage created with the following code(not relevant how it is created, I think):

            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();

            Rectangle screen = transformationContext.getScreen();

            // Create an image that supports transparent pixels
            return gc.createCompatibleImage((int) screen.getWidth(), (int) screen.getHeight(),
                    Transparency.BITMASK);

How do I clear the image(empty image in the same state as it was created) in the fastest way possible without recreating the image? Recreating the image puts a burden on GC, pausing the VM and freezing the UI.

Answer

adrian.tarau picture adrian.tarau · Mar 2, 2010

Got it :) used clearRect instead of fill with a transparent color.

            graphics = (Graphics2D) offlineBuffer.getGraphics();
            graphics.setBackground(new Color(255, 255, 255, 0));
            Rectangle screen = transformationContext.getScreen();
            graphics.clearRect(0,0, (int)screen.getWidth(), (int)screen.getHeight());