添加动画

在屏幕上绘制对象是 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);
}

除非您有在没有用户交互的情况下发生变化的对象,否则通常最好将此标志打开。请做好注释掉此代码的准备,因为下一节将再次使此调用适用。