构建一个GLSurfaceView对象
GLSurface对象是一个特殊的view,本身不会做和绘制图形相关的任务,绘制功能由其内部类GLSurfaceView.Renderer完成。
我们通常可以在Acitvity中创建一个内部类继承GLSurfaceView:
<span style="font-size:14px;">public class MainActivity extends AppCompatActivity {
//
private GLSurfaceView mGLView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGLView = new MyGLSurfaceView(this);
setContentView(mGLView);
}
//GLSurfaceView自己不做太多和绘制图形相关的任务。绘制对象的任务是由GLSurfaceView.Renderer控制
class MyGLSurfaceView extends GLSurfaceView{
private final MyGLRenderer myGLRenderer;
public MyGLSurfaceView(Context context) {
super(context);
// Create an OpenGL ES 2.0 context
setEGLContextClientVersion(2);
myGLRenderer=new MyGLRenderer();
// Set the Renderer for drawing on the GLSurfaceView
setRenderer(myGLRenderer);
//仅在绘制的数据发生变化时才在视图中进行绘制
setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
//不调用这个方法,GLSurfaceView不会重新绘制
requestRender();
}
}</span>
}
继承GLSurfaceView.Renderer(这是渲染类)
onSurfaceCreated()):调用一次,用来配置View的OpenGL ES环境。
onDrawFrame()):每次重新绘制View时被调用。
onSurfaceChanged()):如果View的几何形态发生变化时会被调用,例如当设备的屏幕方向发生改变时
这三个方法是需要重写的。这是仅仅是简单的实现
public class MyGLRenderer implements GLSurfaceView.Renderer {
public void onSurfaceCreated(GL10 unused,EGLConfig config) { // Set the background frame color GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f)(r,g,b,alpha)
; }
public void onDrawFrame(GL10 unused) { // Redraw background color GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); }
public void onSurfaceChanged(GL10 unused, int width, int height) { GLES20.glViewport(0, 0, width, height);
}