如何在AndEngine Rectangle类中实现glColorPointer

时间:2011-11-27 14:46:57

标签: java android opengl-es colors andengine

有人会分享一个关于如何实现每个顶点会有不同颜色的GradienRectangle的例子吗?

我试图从GL10调用glColorPointer传递float buffer和GL11使用类似于顶点的selectOnHardware方法,但这两种方法都失败了...

在AndEngine论坛上我找到了this code,但它不起作用,不过它可以帮助别人找到更好的解决方案。

2 个答案:

答案 0 :(得分:3)

该示例不适合您,因为作者未显示负责设置顶点的代码段。

这是我的例子(很长,但那是opengl ......) 注意 - 记得正确设置启动视口。

public static void drawGradientRectangle(GL10 gl, float centerX, float centerY,
            float width, float height) {
        gl.glPushMatrix();
        gl.glDisable(GL10.GL_TEXTURE_2D);
        gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); //just in case if you have not done that before
        gl.glFrontFace(GL10.GL_CCW); //Set the face

        gl.glTranslatef(centerX, centerY, 0);
        if (width != 1 || height != 1) {
            gl.glScalef(width, height, 1);
        }
        gl.glVertexPointer(2, GL10.GL_FLOAT, 0, GLDrawConstants.vertexBuffer0_5);
        gl.glColorPointer(4, GL10.GL_FLOAT, 0, GLDrawConstants.gradOrangeWhiteBuffer);

        // Draw the vertices as triangle strip
        gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);

        gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
        gl.glEnable(GL10.GL_TEXTURE_2D);
        gl.glPopMatrix();
    }

GLDrawConstants类:

public class GLDrawConstants {

    public static final FloatBuffer gradOrangeWhiteBuffer;
    public static final FloatBuffer vertexBuffer0_5;

private static final float vertices0_5[] = { 
        -0.5f, -0.5f,// Bottom Left
        0.5f, -0.5f,// Bottom right
        -0.5f, 0.5f,// Top Left
        0.5f, 0.5f// Top Right
    };

private static final float gradOrangeWhiteColor[] = {
        255/255f, 239/255f, 196/255f, 0f, // Bottom Left 
        255/255f, 239/255f, 196/255f, 0f, // Bottom right
        250/255f, 200/255f, 62/255f, 0.3f, // Top Left
        250/255f, 200/255f, 62/255f, 0.3f  // Top Right
    };

static {
        gradOrangeWhiteBuffer = WDUtils.floatBuffer(gradOrangeWhiteColor);
        vertexBuffer0_5 = WDUtils.floatBuffer(vertices0_5);
}

}

WDUtils类:

public class WDUtils {
    /**
     * Make a direct NIO FloatBuffer from an array of floats
     * 
     * @param arr
     *            The array
     * @return The newly created FloatBuffer
     */
    public static final FloatBuffer floatBuffer(float[] arr) {
        ByteBuffer bb = ByteBuffer.allocateDirect(arr.length * 4);
        bb.order(ByteOrder.nativeOrder());
        FloatBuffer fb = bb.asFloatBuffer();
        fb.put(arr);
        fb.position(0);
        return fb;
    }
}

example on my phone

答案 1 :(得分:0)

或者您使用(或backport)GLES2-AnchorCenter分支中的Gradient类,这为您提供了超级易用且功能丰富的API,而无需担心OpenGL。 =)