OpenGL学习4

阅读更多

绘制一个3D的三棱锥

 

1.代码

package com.lanhuidong.opengl;

import java.nio.FloatBuffer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import com.lanhuidong.opengl.util.BufferToNativeOrder;

import android.opengl.GLSurfaceView.Renderer;

public class OpenGL3DRender implements Renderer {

    private float unit = 0.5f;
    private float sqrt = (float) Math.sqrt(3);
    private float[] triArray = new float[] {
            0, unit, 0,
            -unit, 0, unit/sqrt, 
            unit, 0, unit/sqrt,

            0, unit, 0, 
            unit, 0, unit/sqrt,
            0, 0, -unit*2*sqrt/3,
            
            0, unit, 0,
            0, 0, -unit*2*sqrt/3,
            -unit, 0, unit/sqrt,
            
            -unit, 0, unit/sqrt,
            unit, 0, unit/sqrt,
            0, 0, -unit*2*sqrt/3
        };
    
    private float colorUnit = 1f;
    private float[] triColor = new float[]{
            colorUnit, 0, 0, colorUnit,
            0, colorUnit, 0, colorUnit,
            0, colorUnit, colorUnit, colorUnit,
            
            colorUnit, 0, 0, colorUnit,
            0, colorUnit, colorUnit, colorUnit,
            colorUnit, 0, colorUnit, colorUnit,
            
            colorUnit, 0, 0, colorUnit,
            0, colorUnit, 0, colorUnit,
            colorUnit, 0, colorUnit, colorUnit,
            
            0, colorUnit, 0, colorUnit,
            0, colorUnit, colorUnit, colorUnit,
            colorUnit, 0, colorUnit, colorUnit
    };
    
    private float triangle = 0f;

    @Override
    public void onDrawFrame(GL10 gl) {
        gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
        gl.glLoadIdentity();
        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
        FloatBuffer floatBuffer = BufferToNativeOrder.getNativeOrderFloatBuffer(triArray);
        gl.glVertexPointer(3, GL10.GL_FLOAT, 0, floatBuffer);
        gl.glColorPointer(4, GL10.GL_FLOAT, 0, BufferToNativeOrder.getNativeOrderFloatBuffer(triColor));
        gl.glRotatef(triangle, 0, 1, 0);
        triangle += 1f;
        for(int i = 0; i < 4; i++){
            gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, i * 3, 3);
        }
        gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
        gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        gl.glViewport(0, 0, width, height);

        float ratio = (float) width / height;
        gl.glMatrixMode(GL10.GL_PROJECTION);
        gl.glLoadIdentity();
        gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10);
    }

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        gl.glClearColor(0, 0, 1.0f, 0.5f);
    }

}

 

2.效果


OpenGL学习4_第1张图片
 

  • OpenGL学习4_第2张图片
  • 大小: 15.5 KB
  • 查看图片附件

你可能感兴趣的:(OpenGL学习4)