设置 GLSurfaceView 和 OpenGL ES 2.0

要在应用程序中使用 OpenGL ES,必须将其添加到清单中:

<uses-feature android:glEsVersion="0x00020000" android:required="true"/>

创建扩展的 GLSurfaceView:

import static android.opengl.GLES20.*; // To use all OpenGL ES 2.0 methods and constants statically

public class MyGLSurfaceView extends GLSurfaceView {
    
    public MyGLSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);

        setEGLContextClientVersion(2); // OpenGL ES version 2.0
        setRenderer(new MyRenderer());
        setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
    }

    public final class MyRenderer implements GLSurfaceView.Renderer{
        public final void onSurfaceCreated(GL10 unused, EGLConfig config) {
            // Your OpenGL ES init methods
            glClearColor(1f, 0f, 0f, 1f);
        }
        public final void onSurfaceChanged(GL10 unused, int width, int height) {
            glViewport(0, 0, width, height);
        }

        public final void onDrawFrame(GL10 unused) {
            // Your OpenGL ES draw methods
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        }
    }
}

MyGLSurfaceView 添加到你的布局:

<com.example.app.MyGLSurfaceView
    android:id="@+id/gles_renderer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

要使用较新版本的 OpenGL ES, 只需在静态导入中更改清单中的版本号,然后更改 setEGLContextClientVersion