opengles(一) hello world

由於項目的要求,需要用到opengles,所以記錄下學習心得,在這裏先寫個opengles 2.0 for android 的 hello world 吧。

在android中需要使用GlSurfaceView來顯示opengles,所以我們先繼承GlSurfaceView來創建一個MyGlSurfaceView。

public class MyGlSurfaceView extends GLSurfaceView {

    public MyGlSurfaceView(Context context) {
        super(context);
        // 創建一個 opengles 2.0 context
        setEGLContextClientVersion(2);
        // 設置使用的渲染器
        setRenderer(new MyRenderer());
        // 設置渲染的模式
        setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
    }

}

setEGLContextClientVersion(2);
在這裏我們使用的是opengles2.0版本,所以需要調用setEGLContextClientVersion來進行聲明;

setRenderer(new MyRenderer());
還需要給GlSurfaceView聲明一個Renderer來具體實現渲染內容, Rnderer是一個接口,是爲了回調GlSurfaceView的渲染過程,我們需要創建一個實現類來實現它裏面的方法。

setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
設置渲染模式,默認是不斷地渲染,即 RENDERMODE_CONTINUOUSLY,這裏用的模式是RENDERMODE_WHEN_DIRTY,意思是只有在明確調用 requestRender 方法時纔會進行渲染;

下面來看下MyRenderer類的實現

public class MyRenderer implements GLSurfaceView.Renderer {
    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        // 設置清空屏幕用的顏色,參數是分別是 R G B A,
        GLES20.glClearColor(0.5f, 0, 0, 1.0f);
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {

    }

    @Override
    public void onDrawFrame(GL10 gl) {
        // 用設置好的顏色來清空緩衝區,參數是指定的緩存區
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
    }
}

onSurfaceCreated 在 surface 創建時被回調,通常用於進行初始化工作,只會被回調一次;
onSurfaceChanged 在每次 surface 尺寸變化時被回調,注意,第一次得知 surface 的尺寸時也會回調;
onDrawFrame 則在繪製每一幀的時候回調。

在這裏我們把GlSurfaceView背景設置爲紅色,完成我們的hello world, 看下activity的代碼,這裏只是把GlSurfaceView 傳入到 setContentView 方法。


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        MyGlSurfaceView sv = new MyGlSurfaceView(this);

        sv.setLayoutParams(new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        setContentView(sv);
    }
}

完成後運行,顯示如下
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章