新增動態效果

在螢幕上繪製物件是 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);
}

除非物件在沒有任何使用者互動的情況下變更,否則建議您啟用這個標記。準備好取消註解這個程式碼,因為下一堂課會再次套用此呼叫。