由于长度不够,这次只打GLEventListener 的代码,整套代码我已经上传了,名为 富视觉的螺旋体.rar,大家可以下载测试一下,这来一个不错的动画,和前面的标准教程不同,这个例子富有视觉和动态,运行效果:程序会自动画螺旋体,然后扩大,背景能变色,gl.glBegin(GL.GL_LINE_STRIP);是本章重点,就是画一条连续不间断的线。其他句子的用法在前面3章都提过。
package com.jogl.second;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.*;
import javax.media.opengl.glu.GLU;
public class LeptospiraGLEventListener implements GLEventListener {
double linelong = 0; //线长
double width = 2;
double height = 2;
//初试化GL界面
public void init(GLAutoDrawable gld) {
GL gl = gld.getGL();
GLU glu = new GLU();
gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
gl.glViewport(-250, -150, 250, 150);
gl.glMatrixMode(GL.GL_PROJECTION);
gl.glLoadIdentity();
glu.gluOrtho2D(-250.0, 250.0, -150.0, 150.0);
}
//画图
public void display(GLAutoDrawable drawable) {
double x, y;
float red = 1.0f;
float green = 0.0f;
float blue = 1.0f;
GL gl = drawable.getGL();
if (linelong == 59 || linelong == 58) {
gl.glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
} else if (linelong == 57 || linelong == 56) {
gl.glClearColor(1.0f, 1.0f, 0.0f, 1.0f);
} else if (linelong == 55 || linelong == 54) {
gl.glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
} else if (linelong == 60) {
gl.glClearColor(1.0f, 1.0f, 0.0f, 1.0f);
} else if (linelong == 00) {
gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
}
gl.glClear(GL.GL_COLOR_BUFFER_BIT);
gl.glColor3f(red, green, blue);
if (linelong < 60) {
linelong += 1;
}
gl.glBegin(GL.GL_LINE_STRIP); //本章重点
if (linelong < 60) { //如果线长小于60
for (double i = 0; i < linelong; i += 0.1) { //这个for语句里画螺旋,由glBegin开始,glEnd
x = Math.sin(i) * i * width;
y = Math.cos(i) * i * height;
gl.glVertex2d(x, y);
}
} else if (linelong == 60 && width < 15 && height < 15) {
width += 0.1;
height += 0.1;
for (double i = 0; i < linelong; i += 0.1) {
x = Math.sin(i) * i * width;
y = Math.cos(i) * i * height;
gl.glVertex2d(x, y);
}
} else if (width >= 15 && height >= 15) {
linelong = 0;
width = 2;
height = 2;
for (double i = 0; i < linelong; i += 0.1) {
x = Math.sin(i) * i * width;
y = Math.cos(i) * i * height;
gl.glVertex2d(x, y);
}
}
gl.glEnd();
gl.glFlush();
}
public void reshape(GLAutoDrawable drawable, int x, int y, int width,
int height) {
}
public void displayChanged(GLAutoDrawable drawable, boolean modeChanged,
boolean deviceChanged) {
}
}
大家可以随便修改代码,,试一下做成其他图形,更酷的更好哦~代码我都发布上了~大家有哪个地方不明白的可以留言,我再重点介绍一下。