Java动画编程基础第四部分

类别:Java 点击:0 评论:0 推荐:

使用图象:
现在,我们将重写paintFrame()来使图象动起来。这也就带来一些
问题,图象往往相当大,被一点点调入,将图象全部画出将花费很多时间,尤其
是通过一个较慢的连接,这也就是为什么drawImage带四个参数的原因,其中
第四个参数为一个ImageObserver对象。通过调用getImage()得到图象。

在屏幕上移动一幅图象:
world.gif作为背景,car.gif作为移动物体,且被绘制了两次,造成
一个两辆车比赛的场景。

Image world;
Image car;

public void init() {
String str = getParameter("fps");
int fps = (str != null) ? Integer.parseInt(str) : 10;
delay = (fps > 0) ? (1000 / fps) : 100;

world = getImage(getCodeBase(), "world.gif");
car = getImage(getCodeBase(), "car.gif");
}

public void paint(Graphics g) {
update(g);
}

public void paintFrame(Graphics g) {
Dimension d = size();
int w = world.getWidth(this);
int h = world.getHeight(this);

if ((w > 0) && (h > 0)) {
g.drawImage(world, (d.width - w)/2, (d.height - h)/2,
this);
}

w = car.getWIdth(this);
h = car.getHeight(this);

if ((w > 0) && (h > 0)) {
w += d.width;
g.drawImage(car, d.width - ((frame * 5) % w),
(d.height - h)/3, this);
g.drawImage(car, d.width - ((frame * 7) % w),
(d.height - h)/2, this);
}
}

显示一系列图象:
通过每一帧显示一幅图象来创建动画。我们仍用双缓冲的方法减小
闪烁。原因是我们显示的每一幅图象有一部分是透明的,因此需要在显示下
一幅前擦除当前的,如果不使用双缓冲的技术将导致闪烁。

Image frames[];
public void init() {
String str = getParameter("fps");
int fps = (str != null) ? Integer.parseInt(str) : 10;
delay = (fps > 0) ? (1000 / fps) : 100;

frames = new Image[10];
for (int i = 0; i < 10; i++) {
frames[i] = getImage(getCodeBase(), "duke/T" + i +
".gif");
}
}

public void paint(Graphics g) {
update(g);
}

public void paintFrame(Graphics g) {
g.drawImage(frames[frame % 10], 0, 0, null);
}

本文地址:http://com.8s8s.com/it/it18856.htm