Android OpenGL ES:展示一张2d图片

前言

本文的环境和条件:GLSurfaceView + OpenGL ES 2.0

代码结构

  1. Activity视图使用GLSurfaceView;
  2. GLSurfaceView使用自定义GLSurfaceView.Render实现,(GLSurfaceView.setRender())
  3. 在Render实现图片纹理化和渲染。

代码Show you the code

自定义的GLSurfaceView.Renderer实现。

public class BitmapRender implements GLSurfaceView.Renderer {
   

    private static final String VERTEX_SHADER =
            "uniform mat4 uMVPMatrix;" +
                    "attribute vec4 aPosition;" +
                    "attribute vec2 aTexCoord;" +
                    "varying vec2 vTexCoord;" +
                    "void main() {" +
                    "  gl_Position = uMVPMatrix * aPosition;" +
                    "  vTexCoord = aTexCoord;" +
                    "}";
    private static final String FRAGMENT_SHADER =
            "precision lowp float;" +
                    "precision highp sampler2D;" +
                    "precision highp int;" +
                    "uniform sampler2D uTextureUnit;" +
                    "varying vec2 vTexCoord;" +
                    "void main() {" +
                    "  gl_FragColor = texture2D(uTextureUnit, vTexCoord);" +
                    "}";
    private static final int COORDS_PRE_VERTEX = 2;
    private static final int COORDS_PRE_TEXTURE = 2;
    // 顶点坐标:世界坐标系
    private static final float[] VERTEX = {
   
            1, 1,  // right, top
            -1, 1, // left, top
            1, -1, // right, bottom
            -1, -1 // left, bottom
    };

    // 纹理坐标
    private static final float[] TEXTUER = {
   
            1, 0.f, // right, top
            0.f, 0.f, // left, top
            1, 1, // right, bottom
            0.f, 1, // left, bottom
    };
    private FloatBuffer mVertexBuffer;
    private FloatBuffer mTextureBuffer;
    private float[] mMVPMatrix = new float[16];
    private int mProgram;
    private int mMVPMatrixHandle;
    private int mPositionHandle;
    private int mTexCoordHandle;
    private Bitmap bitmap;
    private int mBitmapWidth;
    private int mBitmapHeight;
    private int texUnitHandle;
    private int imageTexture = -1;

    public BitmapRender(String imagePath) {
   
        mVertexBuffer = GLESUtils.createFloatBuffer(VERTEX);
        mTextureBuffer = GLESUtils.createFloatBuffer(TEXTUER);
    }

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
   
        //GLES20.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);

        int vertexShader = GLESUtils.createVertexShader(VERTEX_SHADER);
        int fragmentShader = GLESUtils.createFragmentShader(FRAGMENT_SHADER);
        mProgram = GLESUtils.createProgram(vertexShader, fragmentShader);
        // GLES20.glGetAttribLocation方法:获取着

你可能感兴趣的:(OpenGL,ES笔记,Android,android,opengles)