菱形3D实例
下面是具体的实现方法:
首先需要建两个array,第一array是用来告诉opengl这个图形有哪些顶点:
画一个三维的坐标轴,然后把你要画的点都算出来,然后放在这个array里。
package Beta.ThreeD;import java.nio.ByteBuffer;import java.nio.ByteOrder;import java.nio.FloatBuffer;import javax.microedition.khronos.opengles.GL10;public class TriangleShape {private final float l=1.5f;private FloatBuffer fbv;private ByteBuffer ffe;public TriangleShape(){float[] vertex={0.0f,l,0.0f,l,0.0f,0.0f,0.0f,0.0f,l,-l,0.0f,0.0f,0.0f,0.0f,-l,0.0f,-l,0.0f};byte[] edge={0,1,2,1,2,5,0,2,3,5,2,3,0,3,4,5,3,4,0,4,1,5,4,1};ByteBuffer bb = ByteBuffer.allocateDirect(vertex.length*4);bb.order(ByteOrder.nativeOrder());fbv=bb.asFloatBuffer();fbv.put(vertex);fbv.position(0);ffe=ByteBuffer.allocateDirect(edge.length);ffe.put(edge);ffe.position(0);}public void draw(GL10 gl){gl.glFrontFace(GL10.GL_CW);gl.glVertexPointer(3, GL10.GL_FLOAT, 0, fbv);gl.glDrawElements(GL10.GL_TRIANGLES, 24, GL10.GL_UNSIGNED_BYTE, ffe);}}package Beta.ThreeD;import javax.microedition.khronos.egl.EGLConfig;import javax.microedition.khronos.opengles.GL10;import android.opengl.GLSurfaceView.Renderer;public class MySimpleRendered implements Renderer{private int angle=50;private TriangleShape trian;public MySimpleRendered(){trian = new TriangleShape();}@Overridepublic void onDrawFrame(GL10 gl) {// TODO Auto-generated method stubgl.glClear(GL10.GL_COLOR_BUFFER_BIT|GL10.GL_DEPTH_BUFFER_BIT);gl.glMatrixMode(GL10.GL_MODELVIEW);gl.glLoadIdentity();gl.glTranslatef(0, 0, -3.0f);gl.glRotatef(angle,0, 1, 0);gl.glRotatef(angle, 1, 0, 0);gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);trian.draw(gl);angle++;}@Overridepublic void onSurfaceChanged(GL10 gl, int width, int height) {// TODO Auto-generated method stubgl.glViewport(0, 0, width, height);gl.glMatrixMode(GL10.GL_PROJECTION);gl.glLoadIdentity();float ratio = (float)width/height;gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10);}@Overridepublic void onSurfaceCreated(GL10 gl, EGLConfig arg1) {gl.glEnable(GL10.GL_DEPTH_TEST);gl.glClearColor(0,0, 0, 0);}}package Beta.ThreeD;import android.app.Activity;import android.os.Bundle;import android.opengl.GLSurfaceView;public class Triangle extends Activity { /** Called when the activity is first created. */private GLSurfaceView my_view; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); my_view = new GLSurfaceView(this); my_view.setRenderer(new MySimpleRendered()); this.setContentView(my_view); } public void onResume() { super.onResume(); my_view.onResume(); } public void onPause() { super.onPause(); my_view.onPause(); }}