为什么我的三角形不显示在opengl es?

时间:2013-07-08 21:17:42

标签: java android opengl-es

我正在尝试在opengl中显示一个三角形,我已经多次阅读了教程,但我无法弄清楚为什么会发生这种情况。它显示背景而不是三角形,我仔细查看了代码,但是我找不到任何错误。

这是我的MainActivity:

public class MainActivity extends Activity {

GLSurfaceView ourSurface;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ourSurface = new GLSurfaceView(this);
    ourSurface.setRenderer(new GLRenderer());
    setContentView(ourSurface);
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    ourSurface.onPause();
}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    ourSurface.onResume();
}

}

这是我的渲染器:

public class GLRenderer implements Renderer{

private GLTriangle tri;

public GLRenderer(){
    tri = new GLTriangle();
}

@Override
public void onSurfaceCreated(GL10 gl, EGLConfig eglConfig) {
    // TODO Auto-generated method stub
    gl.glDisable(GL10.GL_DITHER);
    gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
    gl.glClearColor(.8f, 0f, .2f, 1f);
    gl.glClearDepthf(1f);
}

@Override
public void onDrawFrame(GL10 gl) {
    // TODO Auto-generated method stub
    gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
    gl.glMatrixMode(GL10.GL_MODELVIEW);
    gl.glLoadIdentity();
    GLU.gluLookAt(gl, 0, 0, -10, 0, 0, 0, 0, 2, 0);
    tri.draw(gl);
}

@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
    // TODO Auto-generated method stub
    gl.glViewport(0, 0, width, height);
    float ratio = (float)width/height;
    gl.glMatrixMode(GL10.GL_PROJECTION);
    gl.glLoadIdentity();
    gl.glFrustumf(-ratio, ratio, -1, 1f, 1, 25);
}

}

这是我的三角形:

public class GLTriangle {
private float vertices[] = {
    0f,1f,
    1f,-1f,
    -1f,-1f
};

private FloatBuffer vertBuff;

private short pIndex[]= {0,1,2};

private ShortBuffer pBuff;

public GLTriangle(){
    ByteBuffer bBuff = ByteBuffer.allocateDirect(vertices.length * 4);
    bBuff.order(ByteOrder.nativeOrder());
    vertBuff = bBuff.asFloatBuffer();
    vertBuff.put(vertices);
    vertBuff.position(0);

    ByteBuffer pbBuff = ByteBuffer.allocateDirect(pIndex.length * 2);
    bBuff.order(ByteOrder.nativeOrder());
    pBuff = pbBuff.asShortBuffer();
    pBuff.put(pIndex);
    pBuff.position(0);
}
public void draw(GL10 gl){
    gl.glFrontFace(GL10.GL_CW);
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glVertexPointer(2, GL10.GL_FLOAT, 0, vertBuff);
    gl.glDrawElements(GL10.GL_TRIANGLES, pIndex.length, GL10.GL_UNSIGNED_SHORT, pBuff);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}

}

1 个答案:

答案 0 :(得分:0)

你必须设置三角形的颜色! 所以必须添加

gl.glColorf(0.5f, 0.9f, 0.2f, 1.0f); //r g b + opacity

在draw方法中,首先是vertexPointer()方法。然后 删除

gl.glSetFrontFace(GL10l.GL_CW);