https://blog.csdn.net/junzia/article/details/52793354
使用版本OpenGL ES2.0支持Android 2.2(API 8)和更高的版本
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
//设置版本
setEGLContextClientVersion(2);
setRenderer(this);
//设置手动刷新
setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
}
//顶点着色器
private String vertexShaderCode = "attribute vec4 vPosition;" +
" void main(){" +
" gl_Position=vPosition;" +
"}";
//片元着色器
private String fragmentShaderCode = "precision mediump float;" +
" uniform vec4 vColor;" +
" void main(){" +
"gl_FragColor=vColor;" +
"}";
float triangleCoords[] = {
0.5f, 0.5f, 0.0f, // top
-0.5f, -0.5f, 0.0f, // bottom left
0.5f, -0.5f, 0.0f // bottom right
};
float color[] = { 1.0f, 1.0f, 1.0f, 1.0f }; //白色
public class MyView extends GLSurfaceView implements GLSurfaceView.Renderer
返回三个方法
onSurfaceCreated、onSurfaceChanged和onDrawFrame
//创建program对象,连接顶点和片元着色器,链接program对象
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
//背景设置为灰色
GLES20.glClearColor(0.5f,0.5f,0.5f,1.0f);
//申请底层空间
ByteBuffer bb = ByteBuffer.allocateDirect(
triangleCoords.length * 4);
bb.order(ByteOrder.nativeOrder());
//将坐标数据转换为FloatBuffer,用以传入给OpenGL ES程序
vertexBuffer = bb.asFloatBuffer();
vertexBuffer.put(triangleCoords);
vertexBuffer.position(0);
int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER,
vertexShaderCode);
int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER,
fragmentShaderCode);
//创建一个空的OpenGLES程序
mProgram = GLES20.glCreateProgram();
//将顶点着色器加入到程序
GLES20.glAttachShader(mProgram,vertexShader);
//将片元着色器加入到程序中
GLES20.glAttachShader(mProgram,fragmentShader);
//链接到着色器程序
GLES20.glLinkProgram(mProgram);
}
public static int loadShader(int shaderType,String source){
int shader= GLES20.glCreateShader(shaderType);
if(0!=shader){
GLES20.glShaderSource(shader,source);
GLES20.glCompileShader(shader);
int[] compiled=new int[1];
GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS,compiled,0);
if(compiled[0]==0){
Log.e("TAG","Could not compile shader:"+shaderType);
Log.e("TAG","GLES20 Error:"+ GLES20.glGetShaderInfoLog(shader));
GLES20.glDeleteShader(shader);
shader=0;
}
}
return shader;
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
GLES20.glViewport(0,0,width,height);
}
@Override
public void onDrawFrame(GL10 gl) {
//程序加入到OpenGLES2.0环境
GLES20.glUseProgram(mProgram);
//获取顶点着色器的vPosition成员句柄
mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");
//启用三角形顶点的句柄
GLES20.glEnableVertexAttribArray(mPositionHandle);
//准备三角形的坐标数据
GLES20.glVertexAttribPointer(mPositionHandle, 3,
GLES20.GL_FLOAT, false,
3*4, vertexBuffer);
//获取片元着色器的vColor成员的句柄
mColorHandle = GLES20.glGetUniformLocation(mProgram,"vColor");
//设置绘制三角形的颜色
GLES20.glUniform4fv(mColorHandle,1,color,0);
//绘制三角形
GLES20.glDrawArrays(GLES20.GL_TRIANGLES,0,3);
//禁止顶点数组的句柄
GLES20.glDisableVertexAttribArray(mPositionHandle);
}