Sometimes you’ll need to uniformly tweak the
alpha values across an entire texture. For example, you may want to create
a fade-in effect or make a texture semitransparent for drawing a heads-up
display (HUD).With OpenGL ES 1.1, this can be achieved simply
by adjusting the current vertex color:
glColor4f(1, 1, 1, alpha);
By default, OpenGL multiplies each component of
the current vertex color with the color of the texel that it’s rendering.
This is known as modulation, and it’s actually only
one of many ways that you can combine texture color with per-vertex color .
If you’re using a texture with premultiplied
alpha, then the vertex color should also be premultiplied. The
aforementioned function call should be changed to the following:
glColor4f(alpha, alpha, alpha, alpha);
Sometimes you may want to throttle back only
one color channel. For example, say your app needs to render some red and
blue buttons and that all the buttons are identical except for their
color. Rather than wasting memory with multiple texture objects, you can
create a single grayscale texture and modulate its color, like
this:
// Bind the grayscale button texture.
glBindTexture(GL_TEXTURE_2D, buttonTexture)
// Draw green button.
glColor4f(0, 1, 0, 1);
glDrawElements(...);
// Draw red button.
glColor4f(1, 0, 0, 1);
glDrawElements(...);
With ES 2.0, the modulation needs to be
performed within the pixel shader itself:
varying lowp vec4 Color;
varying mediump vec2 TextureCoord;
uniform sampler2D Sampler;
void main(void)
{
gl_FragColor = texture2D(Sampler, TextureCoord) * Color;
}