我正在尝试使用以下代码在Android上画一个正方形:
void drawSquare()
{
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
GLfloat vertices[] =
{
-0.5f, -0.5f,
0.5f, -0.5f,
0.5f, 0.5f,
-0.5f, 0.5f
};
GLubyte indices[] = { 0, 1, 2, 3 };
glVertexPointer(2, GL_FLOAT, 0, vertices);
glDrawElements(GL_TRIANGLES, 4, GL_UNSIGNED_BYTE, indices);
}
之前,我调用上面的方法来设置显示器,如:
bool initDisplay()
{
const EGLint attribs[] =
{
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_BLUE_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_RED_SIZE, 8,
EGL_NONE
};
EGLint format;
EGLint numConfigs;
EGLConfig config;
EGLDisplay mDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
eglInitialize(mDisplay, 0, 0);
eglChooseConfig(mDisplay, attribs, &config, 1, &numConfigs);
eglGetConfigAttrib(mDisplay, config, EGL_NATIVE_VISUAL_ID, &format);
ANativeWindow_setBuffersGeometry(mApp->window, 0, 0, format);
EGLSurface mSurface = eglCreateWindowSurface(mDisplay, config, mApp->window, NULL);
EGLContext mContext = eglCreateContext(mDisplay, config, NULL, NULL);
eglMakeCurrent(mDisplay, mSurface, mSurface, mContext);
eglQuerySurface(mDisplay, mSurface, EGL_WIDTH, &mWidth);
eglQuerySurface(mDisplay, mSurface, EGL_HEIGHT, &mHeight);
return true;
}
并像这样设置OpenGL:
bool initGL()
{
glDisable(GL_DITHER);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
glClearColor(0.f, 0.f, 0.f, 1.0f);
glShadeModel(GL_SMOOTH);
glViewport(0, 0, mWidth, mHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
return true;
}
但是,我在屏幕上看不到正方形。刚看到黑屏。预先感谢您的帮助。
索引
GLubyte indices[] = { 0, 1, 2, 3 };
不指定三角形Primitive。指定四边形。分别使用原始类型GL_QUADS
GL_TRIANGLE_FAN
:
GLubyte indices[] = { 0, 1, 2, 3 };
glVertexPointer(2, GL_FLOAT, 0, vertices);
glDrawElements(GL_TRIANGLE_FAN, 4, GL_UNSIGNED_BYTE, indices);
或由具有索引(0-1-2)和(0-2-3)的2个三角形形成正方形:
3 2
+------+ +
| / / |
| / / |
| / / |
+ +-------+
0 1
GLubyte indices[] = { 0, 1, 2, 0, 2, 3 };
glVertexPointer(2, GL_FLOAT, 0, vertices);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, indices);