为什么出现闪烁?
由于组件的重绘会调用update方法,然后由update调用paint方法,由于update的默认情况下操作如下:
1清屏
2设置前景色
3重画
当清屏后我们绘制过程当中,我们就捕捉到了空白的图像,就出现了闪烁。
为什么双缓冲能够减少闪烁?
我们主要改进了第3环节,我们先在后台绘制好图片,放入缓存,我们paint时,只是copy图片,这样速度就提高了。
copy效率高于重新绘制
怎么实现双缓冲?
下面是一段简单的实现,我们重写了paint方法,然后在update中调用它。
public void update (Graphics g){
if (bgImage == null){
bgImage = createImage (this.getSize().width, this.getSize().height); bg = bgImage.getGraphics ();
}
bg.setColor (getBackground ());bg.fillRect (0, 0, this.getSize().width, this.getSize().height);
bg.setColor (getForeground());paint (bg);
g.drawImage (bgImage, 0, 0, this);
}
旅行是一种病。一旦感染了,你就再也无法摆脱。