代码如下:
1、RotateOpenglActivity 类为Activity类
import android.app.Activity;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
public class RotateOpenglActivity extends Activity {
RotateRender rotateRender = new RotateRender();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GLSurfaceView gView = new GLSurfaceView(this);
gView.setRenderer(rotateRender);
setContentView(gView);
}
}
2、渲染类 RotateRender
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.opengl.GLSurfaceView.Renderer;
public class RotateRender implements Renderer {
static int one = 0x10000;
private static IntBuffer trangleBuffer;
private static IntBuffer squreBuffer;
private float mTraRotate = 0.0f;
private float mSquRotate = 0.0f;
//三角形顶点
private int[] vertices = new int[] {
0,one,0,
-one,-one,0,
one,-one,0
};
//正方形顶点
private int[] squres = new int[]{
one,one,0,
-one,one,0,
one,-one,0,
-one,-one,0
};
@Override
public void onDrawFrame(GL10 gl) {
//清除颜色和深度缓存,并重置
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glLoadIdentity();
//设置颜色
gl.glColor4f(0.5f, 0.3f, 0.5f, 1.0f);
//设置缓冲
ByteBuffer tranBuffer = ByteBuffer.allocateDirect(vertices.length * 4);
tranBuffer.order(ByteOrder.nativeOrder());
trangleBuffer = tranBuffer.asIntBuffer();
trangleBuffer.put(vertices);
trangleBuffer.position(0);
ByteBuffer squBuffer = ByteBuffer.allocateDirect(squres.length * 4);
squBuffer.order(ByteOrder.nativeOrder());
squreBuffer = squBuffer.asIntBuffer();
squreBuffer.put(squres);
squreBuffer.position(0);
//开始绘制三角形
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glLoadIdentity();
//允许设置顶点和颜色
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glTranslatef(-1.5f, 0, -6.0f);
gl.glRotatef(mTraRotate, 0.0f, 1.0f, 0.0f);
//设置三角形并绘制
gl.glVertexPointer(3, GL10.GL_FIXED, 0, trangleBuffer);
gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3);
//结束三角形
gl.glFinish();
//重置观察矩阵模型
gl.glLoadIdentity();
gl.glTranslatef(1.5f, 0.0f, -6.0f);
gl.glRotatef(mSquRotate, 1.0f, 0.0f, 0.0f);
gl.glVertexPointer(3, GL10.GL_FIXED, 0, squreBuffer);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
mTraRotate += 0.5f;
mSquRotate += 0.5f;
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
float ratio = (float) width / height;
//场景大小
gl.glViewport(0, 0, width, height);
//投影矩阵
gl.glMatrixMode(GL10.GL_PROJECTION);
//设置视图的大小
gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10);
//选择模型观察矩阵
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
//启用平滑阴影
gl.glShadeModel(GL10.GL_SMOOTH);
//黑屏
gl.glClearColor(0, 0, 0, 0);
//设置深度测试的模型
gl.glDepthFunc(GL10.GL_LEQUAL);
//启用深度模型
gl.glEnable(GL10.GL_DEPTH_TEST);
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
}
}
3、效果图如下: