新增動態效果

在螢幕上繪圖是 OpenGL 的基本功能,但您也可以透過其他方式 Android 圖形架構類別,包括 CanvasDrawable 物件。OpenGL ES 提供額外功能, 在三度空間或其他獨特方式中移動和轉換繪製的物件 引人入勝的使用者體驗

在本課程中,您將瞭解如何新增動態效果,進一步使用 OpenGL ES 轉換成旋轉形狀

旋轉圖案

使用 OpenGL ES 2.0 旋轉繪圖物件相對簡單。在轉譯器中,建立 另一個轉換矩陣 (旋轉矩陣),然後將其與投影與 攝影機視角轉換矩陣:

Kotlin

private val rotationMatrix = FloatArray(16)

override fun onDrawFrame(gl: GL10) {
    val scratch = FloatArray(16)

    ...

    // Create a rotation transformation for the triangle
    val time = SystemClock.uptimeMillis() % 4000L
    val angle = 0.090f * time.toInt()
    Matrix.setRotateM(rotationMatrix, 0, angle, 0f, 0f, -1.0f)

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

    // Draw triangle
    mTriangle.draw(scratch)
}

Java

private float[] rotationMatrix = new float[16];
@Override
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(rotationMatrix, 0, angle, 0, 0, -1.0f);

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

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

如果完成這些變更後,三角形沒有開始旋轉,請確定您已經標示為 GLSurfaceView.RENDERMODE_WHEN_DIRTY 設定,詳情請見下一節。

啟用持續轉譯

此時,如果您堅持使用此類別中的範例程式碼,請 請務必註解排除設定算繪模式的線條,否則只有在骯髒時才會繪製 OpenGL 只旋轉一個形狀,然後等待從 GLSurfaceView 容器呼叫 requestRender()

Kotlin

class MyGLSurfaceView(context: Context) : GLSurfaceView(context) {

    init {
        ...
        // 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:
        // renderMode = GLSurfaceView.RENDERMODE_WHEN_DIRTY
    }
}

Java

public class MyGLSurfaceView(Context context) extends GLSurfaceView {
    ...
    // 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);
}

除非您有物件在沒有任何使用者互動的情況下變更,否則通常建議採用這個做法 旗標已開啟。準備好取消註解這段程式碼了,因為下一堂課將此通話列為適用 同樣地