我想在 Android 设备上使用 OpenGL ES 来显示不同的形状。问题是我的代码甚至不适用于像矩形这样的简单形状(我将在下面使用)。
我认为 somthing 有问题glTranslatef
。我已经调整了所有值,但我无法弄清楚它是什么。
矩形由点定义P(0,0,0), P(0,1,0), P(1,1,0), P(1,0,0)
。在Activity
我实现了GLSurfaceView.Renderer
这样的:
private static FloatBuffer getVertexCoords() {
float coords[] = {
0f, 0f, 0f, // first triangle first point
0f, 1f, 0f, // first triangle second point
1f, 1f, 0f, // first triangle third point
1f, 1f, 0f, // second triangle first point
1f, 0f, 0f, // second triangle second point
0f, 0f, 0f, // second triangle third point
}
ByteBuffer vbb = ByteBuffer.allocateDirect(coords.length * 4); // n coords * 4 bytes per float
vbb.order(ByteOrder.nativeOrder());
FloatBuffer trianglesVB = vbb.asFloatBuffer();
trianglesVB.put(coords);
trianglesVB.position(0);
return trianglesVB;
}
@Override
public void onDrawFrame(GL10 gl) {
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glTranslatef(0f, 0f, -4f);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // glBegin
gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, getVertexCoords());
gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 2 * 3 * 3); // triangles * points * coords
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); // glEnd
int error = gl.glGetError();
if (error != GL10.GL_NO_ERROR) {
Log.e(TAG, "OpenGL ES Error: " + error);
}
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
// think this one doesn't matter
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // white background
gl.glFrontFace(GL10.GL_CW); // front face is clockwise
}