Android OpenGL ES 简明开发教程五:添加颜色

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaozhude/article/details/84578777

前面的例子显示的正方形都是白色,看其来不是很吸引人,本篇介绍如何给Mesh(网格)添加颜色。OpenGL ES使用颜色是我们熟知的RGBA模式(红,绿,蓝,透明度)。

颜色的定义通常使用Hex格式0xFF00FF 或十进制格式(255,0,255), 在OpenGL 中却是使用0…1之间的浮点数表示。 0为0,1相当于255(0xFF)。

最简单的上色方法叫做顶点着色(Vertxt coloring),可以使用单色,也可以定义颜色渐变或者使用材质(类同于二维图形中各种Brush类型)。

Flat coloring(单色)

是通知OpenGL使用单一的颜色来渲染,OpenGL将一直使用指定的颜色来渲染直到你指定其它的颜色。

指定颜色的方法为

public abstract voidglColor4f(float red, float green, float blue, float alpha)。

缺省的red,green,blue为1,代表白色。这也是为什么前面显示的正方形都是白色的缘故。

我们创建一个新的类为FlatColoredSquare,作为Sequare的子类,将它的draw重定义如下:

public void draw(GL10 gl) {

gl.glColor4f(0.5f, 0.5f, 1.0f, 1.0f);

super.draw(gl);

}

将OpenGLRenderer的square的类型改为FlatColoredSquare。

private FlatColoredSquare square=new FlatColoredSquare();

编译运行,正方形颜色变成了蓝色:

Smooth coloring (平滑颜色过渡)

当给每个顶点定义一个颜色时,OpenGL自动为不同顶点颜色之间生成中间过渡颜色(渐变色)。

在项目中添加一个SmoothColoredSquare 类,作为Square子类,为每个顶点定义一个颜色值。

// The colors mapped to the vertices.

float[] colors = {

1f, 0f, 0f, 1f, // vertex 0 red

0f, 1f, 0f, 1f, // vertex 1 green

0f, 0f, 1f, 1f, // vertex 2 blue

1f, 0f, 1f, 1f, // vertex 3 magenta

};

颜色定义的顺序和顶点的顺序是一致的。为了提高性能,和顶点坐标一样,我们也把颜色数组放到Buffer中:

// float has 4 bytes, colors (RGBA) * 4 bytes

ByteBuffer cbb

= ByteBuffer.allocateDirect(colors.length * 4);

cbb.order(ByteOrder.nativeOrder());

colorBuffer = cbb.asFloatBuffer();

colorBuffer.put(colors);

colorBuffer.position(0);

最后修改draw方法,如下:

public void draw(GL10 gl) {

gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);

// Enable the color array buffer to be

//used during rendering.

gl.glEnableClientState(GL10.GL_COLOR_ARRAY);

// Point out the where the color buffer is.

gl.glColorPointer(4, GL10.GL_FLOAT, 0, colorBuffer);

super.draw(gl);

// Disable the color buffer.

gl.glDisableClientState(GL10.GL_COLOR_ARRAY);

}

代码地址GitHub地址

将OpenGLRenderer中的Square类型改成SmoothColoredSquare,编译运行结果如下:

猜你喜欢

转载自blog.csdn.net/xiaozhude/article/details/84578777
今日推荐