Java动画编程基础第三部分

    技术2022-05-11  118

    双缓冲技术:另一种减小帧之间的闪烁的方法是使用双缓冲,它在许多动画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);}}


    最新回复(0)