使用下标画矩阵
运行图
要点
- 修改点的个数,
- 定义索引指向, 0,1,2, 0,2,3
- 绑定 索引buffer 到指定的 target 上面去(GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, indexBufferId);)
- 使用 glDrawElement() 函数来画矩形
做法
-
修改点的个数, 将点的个数修改为4个.
static final float squareCoords[] = { -0.5f, 0.5f, 0.0f, 1, 0, 0, 0.1f, // top left -0.5f, -0.5f, 0.0f, 0, 1, 0, 0.1f, // bottom left 0.5f, -0.5f, 0.0f, 0, 0, 1, 0.1f, // bottom right 0.5f, 0.5f, 0.0f, 1, 1, 0, 0.1f,// top right };
-
定义索引指向,并绑定数据到 buffer
- 定义下标顺序, 3个代表一个三角形.
static final short indexs[] = { 0,1,2, 0,2,3 };
-
绑定下标属性到的 GL_ELEMENT_ARRAY_BUFFER 上面去
IntBuffer intBuffer = IntBuffer.allocate(1);
GLES20.glGenBuffers(1, intBuffer);
indexBufferId = intBuffer.get(0);GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, indexBufferId);
GLES20.glBufferData(GLES20.GL_ELEMENT_ARRAY_BUFFER, indexs.length * 2, indexBuffer, GLES20.GL_STATIC_DRAW);创建 bufferID , 并将bufferID赋值给全局变量, 之后画图的时候调用.
indexBuffer = BufferUtils.newShortBuffer(indexs.length); indexBuffer.put(indexs); indexBuffer.position(0); IntBuffer intBuffer = IntBuffer.allocate(1); GLES20.glGenBuffers(1, intBuffer); indexBufferId = intBuffer.get(0); GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, indexBufferId); GLES20.glBufferData(GLES20.GL_ELEMENT_ARRAY_BUFFER, indexs.length * 2, indexBuffer, GLES20.GL_STATIC_DRAW);
-
绘制
//public static native void glDrawElements( // int mode, // int count, // int type, // int offset //); GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, indexBufferId); GLES20.glDrawElements(GLES20.GL_TRIANGLES, indexs.length , GLES20.GL_UNSIGNED_SHORT, 0);