GLSurfaceView
前言:上篇1.1講解了opengles畫三角形的opengles準備工作屎慢,三角形準備好以后瞭稼,需要一個容器去顯示它忽洛,這篇就理解一下GLSurfaceView
一.GLSurfaceView
GLSurfaceView的使用過程就像是建造房子的過程.
- GLSurfaceView就像是當前建屋所處的地皮
- GlSurfaceView里的Renderer就像是建筑工人,它們會做三件事情:
- onSurfaceCreated() 為建房子做準備工作(水泥环肘,設(shè)備欲虚,搭架等就等同于opengles中準備繪制的圖形,坐標悔雹,顏色等數(shù)據(jù))
- onSurfaceChanged API的解釋是當surface大小改變的時候會去觸發(fā)的复哆,就相當于房子設(shè)計方案
- onDrawFrame 就是具體實施造屋過程了,在Android ondrawFrame繪制每一幀的時候腌零,都會去調(diào)用該函數(shù)梯找,所以在它里面進行不要去申請內(nèi)存
二.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)
{
//設(shè)置視窗大小及位置
GLES20.glViewport(0, 0, width, height);
//計算GLSurfaceView的寬高比
float ratio = (float) width / height;
//調(diào)用此方法計算產(chǎn)生透視投影矩陣
Matrix.frustumM(Triangle.mProjMatrix, 0, -ratio, ratio, -1, 1, 1, 10);
//調(diào)用此方法產(chǎn)生攝像機9參數(shù)位置矩陣
Matrix.setLookAtM(Triangle.mVMatrix, 0, 0,0,3,0f,0f,0f,0f,1.0f,0.0f);
}
public void onSurfaceCreated(GL10 gl, EGLConfig config)
{
//設(shè)置屏幕背景色RGBA
GLES20.glClearColor(0,0,0,1.0f);
//創(chuàng)建三角形對對象
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();
}
}
}
}
}
關(guān)鍵代碼進行說明:
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);
這幾行代碼就構(gòu)成了一個從人眼看物體的場景,其中frustumM是透視投影矩陣益涧,后續(xù)會將到
setLookAtM就是眼睛的位置后續(xù)會將到
到這里繪制三角形的關(guān)鍵點都介紹完了锈锤,下面直接將剩余代碼貼出來即可
三.剩余Android代碼
public class Sample3_1Activity extends Activity
{
MyTDView mview;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//設(shè)置為豎屏模式
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
運行效果為: