Java Doublebuffer - 为什么要清除暴露区域?

时间:2015-08-14 04:14:52

标签: java swing graphics awt

我是Java图形的新手,所以很少有解释会有所帮助。

我在Java双缓冲上找到了这个片段,其中我不明白为什么我们要清除暴露区域,我们刚刚加载了图形。

看起来我们用图形加载它,然后我们清理它?但为什么? (第3个代码块)

任何有关它及其之外的解释都会有所帮助。

class DoubleBufferedCanvas extends Canvas {

    public void update(Graphics g) {
        Graphics offgc;
        Image offscreen = null;
        Dimension d = size();

        // create the offscreen buffer and associated Graphics
        offscreen = createImage(d.width, d.height);
        offgc = offscreen.getGraphics();

        // clear the exposed area  ----------- T H I S    B L O C K --------
        offgc.setColor(getBackground());
        offgc.fillRect(0, 0, d.width, d.height);
        offgc.setColor(getForeground());

        // do normal redraw
        paint(offgc);
        // transfer offscreen to window
        g.drawImage(offscreen, 0, 0, this);
    }
}

1 个答案:

答案 0 :(得分:1)

因为以前涂在屏幕外的图像仍然存在。

首先,这不是Swing,它是AWT

试着这样想一想。在Swing(以及许多其他基于图形的框架)中,工作就像一个最艺术的画布,首先在它上面涂上的东西,除非你先涂上它,否则它仍将保留

让我们仔细看看代码......

// Reference to the image's Graphics context
Graphics offgc;
// Backing image
Image offscreen = null;
// Current size of the component
Dimension d = size();

// create the offscreen buffer and associated Graphics
offscreen = createImage(d.width, d.height);
// Get a reference to the backing buffer's Graphics context
offgc = offscreen.getGraphics();

// The image has a default color (black I think), so we
// fill it with components current background color
// clear the exposed area  ----------- T H I S    B L O C K --------
offgc.setColor(getBackground());
offgc.fillRect(0, 0, d.width, d.height);
// Set the default color to the foreground color
offgc.setColor(getForeground());

// do normal redraw
paint(offgc);
// transfer offscreen to window
g.drawImage(offscreen, 0, 0, this);

现在,paint方法尝试做的事情之一就是不需要它可能会填充Graphics上下文与背景颜色本身。此外,代码不应该调用paint(offgc);,而应该调用super.update(offgc);代替......

我还建议不要使用snipet,而是专注于使用已经双重缓冲的Swing组件或使用BufferStrategyBufferStrategy and BufferCapabilities,如果你想通常控制绘画过程。

另外,请查看Painting in AWT and SwingPerforming Custom Painting,了解有关绘画如何在AWT和Swing中工作的更多详细信息