OPENGL 入门

  • 检测设备支持版本,判断是否支持opengl 2.0版本
  • 初始化设置OpenGLES2.0 
  • 实现接口GLSurfaceView.Renderer 渲染
  • 绘制图形

1、检测设备支持版本,判断是否支持opengl 2.0版本

private boolean hasGLES20(){
    ActivityManager activityManager=(ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
    ConfigurationInfo info=activityManager.getDeviceConfigurationInfo();
    return info.reqGLEsVersion>=0x20000;
}

2、强制应用支持

<uses-feature android:glEsVersion="0x00020000"
              android:required="true"/>

3、初始化设置OpenGLES2.0 

@Override
protected void onCreate(Bundle savedInstanceState){
   //设置全屏模式
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    if(hasGLES20()){
        GLSurfaceView mGLView=new GLSurfaceView(this);
        mGLView.setEGLContextClientVersion(2);
//保留OpenGLESs上下文
        mGLView.setPreserveEGLContextOnPause(true);
        mGLView.setRenderer(new GLES20Renderer());
    }
    super.onCreate(savedInstanceState);
    setContentView(mGLView);
}

//要正常工作,OpenGL 的生命周期要跟Activity 对应上
@Override
protected void onResume() {
super.onResume();
if (mGLView!=null){
mGLView.onResume();
}
}

@Override
protected void onPause() {
super.onPause();
if (mGLView!=null){
mGLView.onPause();
}
}

4、GLSurfaceView.Renderer 渲染器,实现接口GLSurfaceView.Renderer 渲染

public abstract class GLRenderer implements GLSurfaceView.Renderer{
    

private boolean mFirstDraw;
private boolean mSurfaceCreated;
private int mWidth;
private int mHeight;
private long mLastTime;
private int mFPS;
    

@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
    mSurfaceCreated=true;
    mWidth=-1;
    mHeight=-1;
}

@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
    if (!mSurfaceCreated&&width==mWidth&&height==mHeight){
        return;
    }
    mWidth=width;
    mHeight=height;
    onCreate(mWidth,mHeight,mSurfaceCreated);
    mSurfaceCreated=false;
}

@Override
public void onDrawFrame(GL10 gl) {
    onDrawFrame(mFirstDraw);
    if (mFirstDraw){
        mFirstDraw=false;
    }
}
public abstract void onCreate(int width,int height,boolean contextLost);
public abstract void onDrawFrame(boolean firstDraw);
public int getFPS(){
    return mFPS;
}

}

5、绘制图形

public class GLES20Renderer extends GLRenderer {
 
    @Override
    public void onCreate(int width, int height,
            boolean contextLost) {
        GLES20.glClearColor(0f, 0f, 0f, 1f);
    }
 
    @Override
    public void onDrawFrame(boolean firstDraw) {
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT
                | GLES20.GL_DEPTH_BUFFER_BIT);
    }
}

 

posted @ 2019-08-24 12:47  CoCoBill  阅读(215)  评论(0编辑  收藏  举报