GLSurfaceView
前言:上篇1.1讲解了opengles画三角形的opengles准备工作,三角形准备好以后,需要一个容器去显示它,这篇就理解一下GLSurfaceView
一.GLSurfaceView
GLSurfaceView的使用过程就像是建造房子的过程.
- GLSurfaceView就像是当前建屋所处的地皮
- GlSurfaceView里的Renderer就像是建筑工人,它们会做三件事情:
- onSurfaceCreated() 为建房子做准备工作(水泥,设备,搭架等就等同于opengles中准备绘制的图形,坐标,颜色等数据)
- onSurfaceChanged API的解释是当surface大小改变的时候会去触发的,就相当于房子设计方案
- onDrawFrame 就是具体实施造屋过程了,在Android ondrawFrame绘制每一帧的时候,都会去调用该函数,所以在它里面进行不要去申请内存
二.GLSurfaceView具体代码:
public class MyTDView extends GLSurfaceView
{
final float ANGLE_SPAN = 0.375f;
RotateThread rthread;
SceneRenderer mRenderer;
public MyTDView(Context context)
{
super(context);
this.setEGLContextClientVersion(2);
mRenderer=new SceneRenderer();
this.setRenderer(mRenderer);
this.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
}
private class SceneRenderer implements GLSurfaceView.Renderer
{
Triangle tle;
public void onDrawFrame(GL10 gl)
{
//清除深度缓冲与颜色缓冲
GLES20.glClear( GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);
//绘制三角形对
tle.drawSelf();
}
public void onSurfaceChanged(GL10 gl, int width, int height)
{
//设置视窗大小及位置
GLES20.glViewport(0, 0, width, height);
//计算GLSurfaceView的宽高比
float ratio = (float) width / height;
//调用此方法计算产生透视投影矩阵
Matrix.frustumM(Triangle.mProjMatrix, 0, -ratio, ratio, -1, 1, 1, 10);
//调用此方法产生摄像机9参数位置矩阵
Matrix.setLookAtM(Triangle.mVMatrix, 0, 0,0,3,0f,0f,0f,0f,1.0f,0.0f);
}
public void onSurfaceCreated(GL10 gl, EGLConfig config)
{
//设置屏幕背景色RGBA
GLES20.glClearColor(0,0,0,1.0f);
//创建三角形对对象
tle=new Triangle(MyTDView.this);
//打开深度检测
GLES20.glEnable(GLES20.GL_DEPTH_TEST);
rthread=new RotateThread();
rthread.start();
}
}
public class RotateThread extends Thread
{
public boolean flag=true;
@Override
public void run()
{
while(flag)
{
mRenderer.tle.xAngle=mRenderer.tle.xAngle+ANGLE_SPAN;
try
{
Thread.sleep(20);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
}
关键代码进行说明:
GLES20.glViewport(0, 0, width, height);
float ratio = (float) width / height;
Matrix.frustumM(Triangle.mProjMatrix, 0, -ratio, ratio, -1, 1, 1, 10);
Matrix.setLookAtM(Triangle.mVMatrix, 0, 0,0,3,0f,0f,0f,0f,1.0f,0.0f);
这几行代码就构成了一个从人眼看物体的场景,其中frustumM是透视投影矩阵,后续会将到
setLookAtM就是眼睛的位置后续会将到
到这里绘制三角形的关键点都介绍完了,下面直接将剩余代码贴出来即可
三.剩余Android代码
public class Sample3_1Activity extends Activity
{
MyTDView mview;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//设置为竖屏模式
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
mview=new MyTDView(this);
mview.requestFocus();
mview.setFocusableInTouchMode(true);
setContentView(mview);
}
@Override
public void onResume()
{
super.onResume();
mview.onResume();
}
@Override
public void onPause()
{
super.onPause();
mview.onPause();
}
}
这里要注意点就是:在Activity的onResume()和onPause要将GLSurface给onResume和onPause
运行效果为: