簡介
android 中使用 opengles 基本思路:
- 使用
GLSurfaceView
作爲顯示渲染的視圖; - 實現
GLSurfaceView.Renderer
接口,創建自定義的渲染器,然後設置到 GLSurfaceView。
GLSurfaceView 配置
首先確定所使用的 opengles 版本,然後設置指定的渲染器,最後顯示到 Activity 上。
需要注意的是,在 Activity 的生命週期函數中,控制 GLSurfaceView 渲染的開始和暫停。
public class MainActivity extends AppCompatActivity {
private static final String TAG = "opengl-demos";
private static final int GL_VERSION = 3;
private GLSurfaceView glSurfaceView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//初始化 GLSurfaceView
glSurfaceView = new GLSurfaceView(this);
//檢驗是否支持 opengles3.0
if (!checkGLVersion()){
Log.e(TAG, "not supported opengl es 3.0+");
finish();
}
//使用 opengles 3.0
glSurfaceView.setEGLContextClientVersion(GL_VERSION);
//設置渲染器
glSurfaceView.setRenderer(new DemoRender());
//將 GLSurfaceView 顯示到 Activity
setContentView(glSurfaceView);
}
private boolean checkGLVersion(){
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
ConfigurationInfo ci = am.getDeviceConfigurationInfo();
return ci.reqGlEsVersion >= 0x30000;
}
@Override
protected void onResume() {
super.onResume();
//執行渲染
glSurfaceView.onResume();
}
@Override
protected void onPause() {
super.onPause();
//暫停渲染
glSurfaceView.onPause();
}
}
實現渲染器
實現 GLSurfaceView.Renderer
接口即可自定義渲染器。
接口中定義了三個方法:
- onSurfaceCreated:Surface 創建的時候,GLSurfaceView 會調用該方法。程序創建的時候會調用,app切換的時候也有可能調用。
- onSurfaceChanged:Surface 尺寸變化的時候調用,比如橫豎屏切換的時候。
- onDrawFrame:繪製幀。
public class DemoRender implements GLSurfaceView.Renderer {
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
//清空屏幕所用的顏色
GLES30.glClearColor(1.0f, 0f, 0f, 0f);
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
//設置適口尺寸
GLES30.glViewport(0,0,width,height);
}
@Override
public void onDrawFrame(GL10 gl) {
//使用 glClearColor 指定的顏色擦除屏幕
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT);
}
}
總結
本文梳理了 android 下使用 opengles 的基本流程及核心類的使用,顯示了一個純色窗口。