Android使用OpenGL ES添加移動(dòng)

2018-08-02 17:37 更新

編寫:jdneo - 原文:http://developer.android.com/training/graphics/opengl/motion.html

在屏幕上繪制圖形是OpenGL的一個(gè)基本特性,當(dāng)然我們也可以通過其它的Android圖形框架類做這些事情,包括CanvasDrawable對(duì)象。OpenGL ES的特別之處在于,它還提供了其它的一些功能,比如在三維空間中對(duì)繪制圖形進(jìn)行移動(dòng)和變換操作,或者通過其它獨(dú)有的方法創(chuàng)建出引人入勝的用戶體驗(yàn)。

在這節(jié)課中,我們會(huì)更深入地學(xué)習(xí)OpenGL ES的知識(shí):對(duì)一個(gè)圖形添加旋轉(zhuǎn)動(dòng)畫。

旋轉(zhuǎn)一個(gè)形狀

使用OpenGL ES 2.0 旋轉(zhuǎn)一個(gè)繪制圖形是比較簡(jiǎn)單的。在渲染器中,創(chuàng)建另一個(gè)變換矩陣(一個(gè)旋轉(zhuǎn)矩陣),并且將它和我們的投影變換矩陣以及相機(jī)視角變換矩陣結(jié)合在一起:

private float[] mRotationMatrix = new float[16];
public void onDrawFrame(GL10 gl) {
    float[] scratch = new float[16];

    ...

    // Create a rotation transformation for the triangle
    long time = SystemClock.uptimeMillis() % 4000L;
    float angle = 0.090f * ((int) time);
    Matrix.setRotateM(mRotationMatrix, 0, angle, 0, 0, -1.0f);

    // Combine the rotation matrix with the projection and camera view
    // Note that the mMVPMatrix factor *must be first* in order
    // for the matrix multiplication product to be correct.
    Matrix.multiplyMM(scratch, 0, mMVPMatrix, 0, mRotationMatrix, 0);

    // Draw triangle
    mTriangle.draw(scratch);
}

如果完成了這些變更以后,你的三角形還是沒有旋轉(zhuǎn)的話,確認(rèn)一下你是否將啟用GLSurfaceView.RENDERMODE_WHEN_DIRTY的這一配置所對(duì)應(yīng)的代碼注釋掉了,有關(guān)該方面的知識(shí)會(huì)在下一節(jié)中展開。

啟用連續(xù)渲染

如果嚴(yán)格按照這節(jié)課的樣例代碼走到了現(xiàn)在這一步,那么請(qǐng)確認(rèn)一下是否將設(shè)置渲染模式為RENDERMODE_WHEN_DIRTY的那行代碼注釋了,不然的話OpenGL只會(huì)對(duì)這個(gè)形狀執(zhí)行一次旋轉(zhuǎn),然后就等待GLSurfaceView容器的requestRender())方法被調(diào)用后才會(huì)繼續(xù)執(zhí)行渲染操作。

public MyGLSurfaceView(Context context) {
    ...
    // Render the view only when there is a change in the drawing data.
    // To allow the triangle to rotate automatically, this line is commented out:
    //setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
}

除非某個(gè)對(duì)象,它的變化和用戶的交互無關(guān),不然的話一般還是建議將這個(gè)配置打開。在下一節(jié)課中的內(nèi)容將會(huì)把這個(gè)注釋放開,再次設(shè)定這一配置選項(xiàng)。


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)