嗨,我是android open gl的新手。我尝试在open gles 2.0中创建几个2d对象。现在我试图在android open gles 2.0中绘制一条线。我的代码看起来像
public class UserLine
{
private final String vertexShaderCode =
"uniform mat4 uMVPMatrix;" +
"attribute vec4 vPosition;" +
"void main() {" +
" gl_Position = uMVPMatrix * vPosition;" +
"}";
private final String fragmentShaderCode =
"precision mediump float;" +
"uniform vec4 vColor;" +
"void main() {" +
" gl_FragColor = vColor;" +
"}";
private final FloatBuffer vertexBuffer;
private final ShortBuffer drawListBuffer;
private final int mProgram;
private int mPositionHandle;
private int mColorHandle;
private int mMVPMatrixHandle;
static final int COORDS_PER_VERTEX = 3;
private final int vertexStride = COORDS_PER_VERTEX * 4;
private float[] pathCords =
{
0.00f, 0.0f, 0.0f,
0.5f, 0.3f, 0.0f
};
private short[] pathDrawOrder = {0,1}
private float[] color = {1.0f, 0.0f, 0.0f, 1.0f};
public UserLine()
{
ByteBuffer bb = ByteBuffer.allocateDirect(pathCords.length * 4);
bb.order(ByteOrder.nativeOrder());
vertexBuffer = bb.asFloatBuffer();
vertexBuffer.put(pathCords);
vertexBuffer.position(0);
ByteBuffer dlb = ByteBuffer.allocateDirect(pathDrawOrder.length * 2);
dlb.order(ByteOrder.nativeOrder());
drawListBuffer = dlb.asShortBuffer();
drawListBuffer.put(pathDrawOrder);
drawListBuffer.position(0);
int vertexShader = MyGLRenderer.loadShader(GLES20.GL_VERTEX_SHADER,vertexShaderCode);
int fragmentShader = MyGLRenderer.loadShader(GLES20.GL_FRAGMENT_SHADER,fragmentShaderCode);
mProgram = GLES20.glCreateProgram();
GLES20.glAttachShader(mProgram, vertexShader);
GLES20.glAttachShader(mProgram, fragmentShader);
GLES20.glLinkProgram(mProgram);
}
public void draw(float[] mvpMatrix) {
GLES20.glUseProgram(mProgram);
mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");
GLES20.glEnableVertexAttribArray(mPositionHandle);
GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX,GLES20.GL_FLOAT, false,
vertexStride, vertexBuffer);
mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");
GLES20.glUniform4fv(mColorHandle, 1, color, 0);
mMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0);
GLES20.glDrawElements(GLES20.GL_LINES, color.length,
GLES20.GL_UNSIGNED_SHORT, drawListBuffer);
GLES20.glDisableVertexAttribArray(mPositionHandle);
GLES20.glDisable(mColorHandle);
}
}
所以这是我的问题根据这段代码,它必须绘制一条线,但沿着该线它还会绘制一条额外的线,这不是预期的行为。
我做错了什么或是默认行为。需要帮忙。谢谢。
答案 0 :(得分:3)
我认为问题在于:
GLES20.glDrawElements(GLES20.GL_LINES, color.length, GLES20.GL_UNSIGNED_SHORT, drawListBuffer);
第二个参数是计数,我不明白为什么你把它设置为颜色的长度。这只是您传递到着色器的线条的颜色,因此长度始终为4:
private float[] color = {1.0f, 0.0f, 0.0f, 1.0f};
你正在使用pathDrawOrder中指定的2个点绘制一条线,所以我认为使用它的长度代替你所需要的:
GLES20.glDrawElements(GLES20.GL_LINES, pathDrawOrder.length, GLES20.GL_UNSIGNED_SHORT, drawListBuffer);