正式开始,在安卓开发中,最简单的openGL使用就3步:
继承GLSurfaceView
实现接口 GLSurfaceView.Renderer
布局中引用
来,敲代码,这里以实现绘制一屏红色为例。
1.继承GLSurfaceView
自定义一个View,新建一个类,继承GLSurfaceView,在构造方法里调用GLSurfaceView的setRenderer方法。
package com.york.media.opengl.egl;import android.content.Context;import android.opengl.GLSurfaceView;import android.util.AttributeSet;/**
* author : York
* date : 2020/12/17 21:57
* desc : 最简单的OpenGL使用方法
*/public class YGLSurfaceView extends GLSurfaceView { public YGLSurfaceView(Context context) { super(context); } public YGLSurfaceView(Context context, AttributeSet attrs) { super(context, attrs); //1.自定义的 Render,在 Render中实现绘制 YGLRender yGLRender = new YGLRender(); //2.调用 GLSurfaceView的setRenderer方法 setRenderer(yGLRender); }}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2.实现 GLSurfaceView.Renderer 接口
自定义一个 Render,实现GLSurfaceView.Renderer接口,然后在 Render中完成绘制。
package com.york.media.opengl.egl;import android.opengl.GLES20;import android.opengl.GLSurfaceView;import javax.microedition.khronos.egl.EGLConfig;import javax.microedition.khronos.opengles.GL10;/**
* author : York
* date : 2020/12/17 21:58
* desc : Render中使用红色清屏
*/public class YGLRender implements GLSurfaceView.Renderer { public YGLRender() { } @Override public void onSurfaceCreated(GL10 gl10, EGLConfig eglConfig) { } @Override public void onSurfaceChanged(GL10 gl10, int with, int height) { GLES20.glViewport(0, 0, with, height); } @Override public void onDrawFrame(GL10 gl10) { //使用红色清屏 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); GLES20.glClearColor(1f,0f,0f,1f); }}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
布局中引用自定义的GLSurfaceView
最后,在布局中引用自定义的GLSurfaceView,就可以显示出红色了。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <com.york.media.opengl.egl.YGLSurfaceView
android:layout_width="match_parent" android:layout_height="match_parent"/>
1
2
3
4
5
6
7
8
9
10
11
12
效果是这样的: