android opengl es画三角形-native C实现
Native C开发opengl,网上这方面的资料很少,研究了几天才弄出来,现在贴出来供交流,转载请注明Hello Xiexh
#include <stdio.h>
#include <unistd.h>
#include <EGL/egl.h>
#include <GLES/gl.h>
#include<ui/FramebufferNativeWindow.h>
#include <ui/EGLUtils.h>
#include <ui/DisplayInfo.h>
#include <surfaceflinger/SurfaceComposerClient.h>
using namespace android;
int mWidth;
int mHeight;
EGLDisplay mDisplay;
EGLDisplay mContext;
EGLDisplay mSurface;
sp<SurfaceControl>mFlingerSurfaceControl;
sp<Surface> mFlingerSurface;
int initGraphics()
{
//create the native surface
sp<SurfaceComposerClient>session = new SurfaceComposerClient();
DisplayInfodinfo;
status_tstatus = session->getDisplayInfo(0, &dinfo);
if(status)
return-1;
sp<SurfaceControl> control = session->createSurface(
getpid(), 0, 400, 300, PIXEL_FORMAT_RGB_565);
session->openTransaction();
control->setLayer(0x40000000);
session->closeTransaction();
sp<Surface> s = control->getSurface();
//initialize opengl and egl
constEGLint attribs[] = {
EGL_DEPTH_SIZE,0,
EGL_NONE
};
EGLintw, h, dummy;
EGLintnumConfigs;
EGLConfigconfig;
EGLSurfacesurface;
EGLContextcontext;
EGLDisplaydisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
eglInitialize(display,0, 0);
EGLUtils::selectConfigForNativeWindow(display,attribs, s.get(), &config);
surface= eglCreateWindowSurface(display, config, s.get(), NULL);
context= eglCreateContext(display, config, NULL, NULL);
eglQuerySurface(display,surface, EGL_WIDTH, &w);
eglQuerySurface(display,surface, EGL_HEIGHT, &h);
if(eglMakeCurrent(display, surface, surface, context) == EGL_FALSE)
returnNO_INIT;
mDisplay= display;
mContext= context;
mSurface= surface;
mWidth= w;
mHeight= h;
mFlingerSurfaceControl= control;
mFlingerSurface= s;
glViewport(0,0, mWidth, mHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrthof(0,mWidth, 0, mHeight, 0, 1);
return EGL_TRUE;
}
void draw() {
//printf("startdrawing...\n");
glColor4f(1,0,0,1);
const GLfloat vertices[3][2] = {
{100, 100},
{200, 100},
{100,200}
};
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, vertices);
glClearColor(0,0,0,0);
glClear(GL_COLOR_BUFFER_BIT);
glDrawArrays(GL_TRIANGLES, 0, 3);
eglSwapBuffers(mDisplay, mSurface);
}
int main(int argc, char** argv) {
if(!initGraphics())
{
printf("Graphicsinitialization failed.\n");
returnEXIT_FAILURE;
}
while(1){
draw();
usleep(100*1000);
}
//clearstatus
eglMakeCurrent(mDisplay,EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
eglDestroyContext(mDisplay,mContext);
eglDestroySurface(mDisplay,mSurface);
mFlingerSurface.clear();
mFlingerSurfaceControl.clear();
eglTerminate(mDisplay);
return0;
}
Android.mk :
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
LOCAL_SRC_FILES:= \
opengl_test.cpp
LOCAL_SHARED_LIBRARIES := \
libutils\
libui \
libEGL \
libGLESv1_CM \
libsurfaceflinger_client
LOCAL_MODULE := xxhtest
LOCAL_MODULE_TAGS:= optional
include $(BUILD_EXECUTABLE)