GLSurfaceView 绘制三角形
GLSurfaceView 的渲染类
public class MyRenderer implements Renderer {
private TriangleHelp triangleHelp;
@Override
public void onDrawFrame(GL10 gl) {
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
triangleHelp.draw(gl);
}
@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);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
gl.glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
gl.glShadeModel(GL10.GL_SMOOTH);
gl.glClearDepthf(1.0f);
gl.glEnable(GL10.GL_DEPTH_TEST);
gl.glDepthFunc(GL10.GL_LEQUAL);
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
triangleHelp = new TriangleHelp();
}
}
用于绘制三角形的帮助类
public class TriangleHelp {
private FloatBuffer triangleBuffer;
private FloatBuffer colorBuffer;
private float[] triangleArray = {
0f, 1f, 0f,
-1f, -1f, 0f,
1f, -1f, 0f
};
private float[] colorArray={
1f,0f,0f,1f,
0f,1f,0f,1f,
0f,0f,1f,1f
};
public TriangleHelp(){
triangleBuffer = BufferUtil.floatToBuffer(triangleArray);
colorBuffer = BufferUtil.floatToBuffer(colorArray);
}
public void draw(GL10 gl){
gl.glColorPointer(4, GL10.GL_FLOAT, 0, colorBuffer);
gl.glLoadIdentity();
gl.glTranslatef(-2f, 0.0f, -8.0f);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, triangleBuffer);
gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3);
gl.glFinish();
}
}
工具类
public class BufferUtil {
public static FloatBuffer floatToBuffer(float[] array){
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(array.length * 4);
byteBuffer.order(ByteOrder.nativeOrder());
FloatBuffer floatBuffer = byteBuffer.asFloatBuffer();
floatBuffer.put(array);
floatBuffer.position(0);
return floatBuffer;
}
public static IntBuffer intToBuffer(int[] array){
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(array.length * 4);
byteBuffer.order(ByteOrder.nativeOrder());
IntBuffer intBuffer = byteBuffer.asIntBuffer();
intBuffer.put(array);
intBuffer.position(0);
return intBuffer;
}
}