快捷搜索:

Java动画编程基础第三部分

双缓冲技巧:

另一种减小帧之间的闪烁的措施是应用双缓冲,它在许多动画applet

中被应用。

主要道理是创建一个后台图象,将一帧画入图象,然后调用drawImage()

将全部图象一次画到屏幕上去。好处是大年夜部分绘制是离屏的。将离屏图象一次

绘至屏幕上比直接在屏幕上绘制要有效得多。

双缓冲可以使动画平滑,但有一个毛病,要分配一张后台图象,假如图象

相昔时夜,这将必要很大年夜一块内存。

当你应用双缓冲技巧时,应重载update()。

Dimension offDimension;

Image offImage;

Graphics offGraphics;

public void update(Graphics g) {

Dimension d = size();

if ((offGraphics == null)

|| (d.width != offDimension.width)

|| (d.height != offDimension.height)) {

offDimension = d;

offImage = createImage(d.width, d.height);

offGraphics = offImage.getGraphics();

}

offGraphics.setColor(getBackground());

offGraphics.fillRect(0, 0, d.width, d.height);

offGraphics.setColor(Color.Black);

paintFrame(offGraphics);

g.drawImage(offImage, 0, 0, null);

}

public void paint(Graphics g) {

if (offImage != null) {

g.drawImage(offImage, 0, 0, null);

}

}

public void paintFrame(Graphics g) {

Dimension d = size();

int h = d.height / 2;

for (int x = 0; x < d.width; x++) {

int y1 = (int)((1.0 + Math.sin((x - frame) *

0.05)) + h);

int y2 = (int)((1.0 + Math.sin((x + frame) *

0.05)) + h);

g.drawLine(x, y1, x, y2);

}

}

您可能还会对下面的文章感兴趣: