标签:glsurfaceview opengl es shader 着色器 android渲染
在定义了将要被OpenGL绘制的形状之后,你当然想要绘制它们。使用OpenGL ES 2.0绘制图形需要的代码可能比你想象的要多,因为API提供了大量的图形渲染管道控制接口。public void onSurfaceCreated(GL10 unused, EGLConfig config) {
...
// initialize a triangle
mTriangle = new Triangle();
// initialize a square
mSquare = new Square();
}
Vertex Shader - OpenGL ES graphics code for rendering the vertices of a shape.你至少需要一个顶点着色器来绘制形状,一个片元着色器来对形状着色。这些着色器必须被编译和被添加到OpenGL ES程序中。下面是一个如何通过定义着色器来绘制图形的例子:
译:顶点着色器 - 渲染形状顶点的OpenGL ES图形代码
Fragment Shader - OpenGL ES code for rendering the face of a shape with colors or textures.
译:片元着色器 - 使用颜色或者纹理渲染形状表面的OpenGL ES图形代码
Program - An OpenGL ES object that contains the shaders you want to use for drawing one or more shapes.
译:Program - 包含了用来绘制形状的着色器的OpenGL ES对象
private final String vertexShaderCode =着色器使用了OpenGL着色语言(GLSL)代码,在OpenGL ES环境中使用之前必须被编译,为了编译这些代码,在你的renderer类中创建一个方法:
"attribute vec4 vPosition;" +
"void main() {" +
" gl_Position = vPosition;" +
"}";
private final String fragmentShaderCode =
"precision mediump float;" +
"uniform vec4 vColor;" +
"void main() {" +
" gl_FragColor = vColor;" +
"}";
public static int loadShader(int type, String shaderCode){
// create a vertex shader type (GLES20.GL_VERTEX_SHADER)
// or a fragment shader type (GLES20.GL_FRAGMENT_SHADER)
int shader = GLES20.glCreateShader(type);
// add the source code to the shader and compile it
GLES20.glShaderSource(shader, shaderCode);
GLES20.glCompileShader(shader);
return shader;
}
public class Triangle() {
...
int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);
mProgram = GLES20.glCreateProgram(); // create empty OpenGL ES Program
GLES20.glAttachShader(mProgram, vertexShader); // add the vertex shader to program
GLES20.glAttachShader(mProgram, fragmentShader); // add the fragment shader to program
GLES20.glLinkProgram(mProgram); // creates OpenGL ES program executables
}
public void draw() {
// Add program to OpenGL ES environment
GLES20.glUseProgram(mProgram);
// get handle to vertex shader‘s vPosition member
mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");
// Enable a handle to the triangle vertices
GLES20.glEnableVertexAttribArray(mPositionHandle);
// Prepare the triangle coordinate data
GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX,
GLES20.GL_FLOAT, false,
vertexStride, vertexBuffer);
// get handle to fragment shader‘s vColor member
mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");
// Set color for drawing the triangle
GLES20.glUniform4fv(mColorHandle, 1, color, 0);
// Draw the triangle
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount);
// Disable vertex array
GLES20.glDisableVertexAttribArray(mPositionHandle);
}
Android OpenGL ES绘图教程之三 : 绘制图形
标签:glsurfaceview opengl es shader 着色器 android渲染
原文地址:http://blog.csdn.net/fanfanxiaozu/article/details/45196559