GLSurfaceView使用之第二篇画三角形

来源:互联网 发布:python元组转换为列表 编辑:程序博客网 时间:2024/05/21 19:44
import java.nio.ByteBuffer;import java.nio.ByteOrder;import java.nio.FloatBuffer;import javax.microedition.khronos.egl.EGLConfig;import javax.microedition.khronos.opengles.GL10;import android.app.Activity;import android.opengl.GLSurfaceView;import android.opengl.GLU;import android.os.Bundle;import android.util.Log;public class MainActivity extends Activity {private final String TAG = "MainActivity";private GLSurfaceView glSurefaceView;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);glSurefaceView = new GLSurfaceView(this);glSurefaceView.setRenderer(new GLSurfaceViewRender());this.setContentView(glSurefaceView);}@Overrideprotected void onResume() {super.onResume();glSurefaceView.onResume();}@Overrideprotected void onPause() {super.onStop();glSurefaceView.onPause();}class GLSurfaceViewRender implements GLSurfaceView.Renderer {@Overridepublic void onSurfaceCreated(GL10 gl, EGLConfig config) {Log.i(TAG, "onSurfaceCreated");// 设置背景颜色gl.glClearColor(0.0f, 0f, 0f, 0.5f);// 启用顶点数组(否则glDrawArrays不起作用)gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);}@Overridepublic void onSurfaceChanged(GL10 gl, int width, int height) {Log.i(TAG, "onSurfaceChanged");// 设置输出屏幕大小gl.glViewport(0, 0, width, height);}private float[] mTriangleArray = {// X, Y, Z 这是一个等边三角形-0.5f, -0.25f, 0, 0.5f, -0.25f, 0, 0.0f, 0.559016994f, 0 };@Overridepublic void onDrawFrame(GL10 gl) {Log.i(TAG, "onDrawFrame");// 清除屏幕和深度缓存(如果不调用该代码, 将不显示glClearColor设置的颜色)// 同样如果将该代码放到 onSurfaceCreated 中屏幕会一直闪动gl.glClear(GL10.GL_COLOR_BUFFER_BIT);gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f);FloatBuffer mTriangleBuffer = BufferUtil.floatToBuffer(mTriangleArray);gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mTriangleBuffer);gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3);//gl.glLoadIdentity();// 平移 (矩阵相乘)gl.glTranslatef(-0.2f, 0.3f, 0f);}}static class BufferUtil {public static FloatBuffer mBuffer;public static FloatBuffer floatToBuffer(float[] a) {// 先初始化buffer,数组的长度*4,因为一个float占4个字节ByteBuffer mbb = ByteBuffer.allocateDirect(a.length * 4);// 数组排序用nativeOrdermbb.order(ByteOrder.nativeOrder());mBuffer = mbb.asFloatBuffer();mBuffer.put(a);mBuffer.position(0);return mBuffer;}}}