六、设置窗口宽高比例
你必须设置窗口的宽高比例以使对象能够正确着色。列表3中的代码是未改动的-基本上同Sun的例子一样。首先,检查画布的宽度和高度,然后根据相机的类型来计算宽高比例。
列表3. 设置宽高比例
void setupAspectRatio() {
viewport_x = 0;
viewport_y = 0;
viewport_width = myCanvas.getWidth();
viewport_height = myCanvas.getHeight();
Camera cam = myWorld.getActiveCamera();
float[] params = new float[4];
int type = cam.getProjection(params);
if(type != Camera.GENERIC) {
//计算窗口的宽高比
float waspect=viewport_width/viewport_height;
if (waspect float height = viewport_width/params[1];
viewport_height=(int)height;
viewport_y=(myCanvas.getHeight()-viewport_height)/2;
}
else {
float width = viewport_height*params[1];
viewport_width=(int)width;
viewport_x=(myCanvas.getWidth()-viewport_width)/2;
}
}
}
七、刷新视图
为了刷新视图,你可以用TimerTask来调用画布的repaint()方法。另一种方法是直接使用线程,然后创建ExampleCanvas(画布类的名字)来实现Runnable接口。
列表4. 刷新视图
private class RefreshTask extends TimerTask
{
public void run(){
if(myCanvas != null && myGraphics3D != null && myWorld != null) {
int startTime = (int)System.currentTimeMillis();
int validity = myWorld.animate(startTime);
myCanvas.repaint(viewport_x, viewport_y, viewport_width, viewport_height);
}
}
}