新闻正文

一起学Java (二 ).(动画)

来源:JAVA天堂  JAVA学习者  2007-4-22 02:32:54 网友评论 0 条 字体:[ ] ~我要投稿!
锦城驿站 (Wed Jul 30 05:38:55 1997)
转信站: sjtubbs!sjtunews!swjtunews!swjtubbs
Origin: xnjd21.swjtu.edu.cn
画出每一帧:
剩下的就是将每一帧图象绘出。在上例中调用了applet的repaint()来绘出
每一帧图象。
public void paint(Graphics g) {
g.setColor(Color.red);
g.drawString("animator = " + frame, 0, 30);
}

完整代码如下:
import java.awt.*;
import java.applet.*;
import java.util.*;
public class animator02 extends java.applet.Applet implements Runnable {
int frame;
int delay;
Thread animator;
public void init() {
String str = getParameter("fps");
int fps = (str != null) ? Integer.parseInt(str) : 10;
delay = (fps > 0) ? (1000 / fps) : 100;
}
public void start() {
animator = new Thread(this);
animator.start();
}

public void run() {
while (Thread.currentThread() == animator) {
repaint();
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
break;
}
frame++;
if (frame > 9999) frame = 0;
}
}
public void stop() {
animator = null;
}
public void paint(Graphics g) {
g.setColor(Color.red);
g.drawString("animator = " + frame, 0 , 30);
}
}
生成图形:
现在我们来画一些稍微困难的东西。下例画了一个正弦曲线的组合,
对于每一个x,画一条短的垂直线,所有这些线组成了一个图形,并且每帧变化。
但不幸有些闪动,在以后我们将解释为什么闪以及怎样避免。
public void paint(Graphics g) {
Dimension d = size();
int h = d.height / 2;

g.setColor(Color.red);
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);
}
}

避免闪烁:
上例中的闪烁有两个原因:绘制每一帧花费的时间太长(因为重绘时要
求的计算量大),二是在每次调用pait()前整个背景被清除,当在进行下一帧的
计算时,用户看到的是背景。
清除背景和绘制图形间的短暂时间被用户看见,就是闪烁。在有些平台如PC
机上闪烁比在X Window上明显,这是因为X Window的图象被缓存过,使得闪烁的时
间比较短。
有两种办法可以明显地减弱闪烁:重载update()或使用双缓冲。
重载update():
当AWT接收到一个applet的重绘请求时,它就调用applet的update()。缺省
地,update()清除applet的背景,然后调用paint()。重载update(),将以前在paint()中
的绘图代码包含在update()中,从而避免每次重绘时将整个区域清除。

既然背景不在自动清除,我们需要自己在update()中完成。我们在绘制
新的线之前独自将竖线擦除,完全消除了闪烁。
public void paint(Graphics g) {
update(g);
}
public void update(Graphics g) {
Color bg = getBackground();
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);
if (y1 > y2) {
int t = y1;
y1 = y2;
y2 = t;
}
g.setColor(bg);
g.drawLine(x, 0, x, y1);
g.drawLine(x, y2, x, d.height);
g.setColor(Color.red);
g.drawLine(x, y1, x, y2);
}
}

(o<~ ~>o) L ("< >`) N >~)/ /_
/ ) A ( / ) E ( ^^
--/ ^^------^^ ---L-----^-----------
.[FROM: 202.115.66.19]


收藏到ViVi   收藏此页到365Key
上一篇: 一起学Java (一).(动画)
下一篇: Java Applet 计数器(摘自computer world)
用户名:新注册) 密码: 匿名评论 [所有评论]
评论内容:不能超过250字,需审核后才会公布,请自觉遵守互联网相关政策法规。
本栏搜索
  • Google
   网站首页 -  网站地图 -  技术学习 -  网站投稿 -  帮助中心
Copyright 2003-2008 www.javah.net All Rights Reserved
2008 如果你喜欢本站 请收藏本站 并推荐给你的朋友一起分享