当前位置: 首页 > 图灵资讯 > 技术篇> Java动画编程基础第三部分

Java动画编程基础第三部分

来源:图灵教育
时间:2024-02-28 17:21:15

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