stealthcopter
stealthcopter

Reputation: 14206

Android Getting correct opacity/colors with glBlendFunc blending in OpenGL-ES

In my program I want to draw a square (with varying opacity, lets say red for arguments sake) onto a textured background. However the square appears the wrong color depending on the background. With alpha=1.0f (opaque) the square should appear red, which it does on a black background but on a white background it appears white (and scales accordingly in-between)

In my GLActivity have set the following flags:

gl.glDisable(GL10.GL_LIGHTING);
gl.glDisable(GL10.GL_CULL_FACE);
gl.glDisable(GL10.GL_DEPTH_BUFFER_BIT);
gl.glDisable(GL10.GL_DEPTH_TEST);
gl.glEnable(GL10.GL_DITHER);
gl.glShadeModel(GL10.GL_SMOOTH);
gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE);

Then I draw the background texture:

gl.glClearColor(0.0f,0.0f,0.0f,1.0f);


gl.glBindTexture(GL10.GL_TEXTURE_2D, texturesFPS[1]);
 gl.glEnable(GL10.GL_TEXTURE_2D);

 gl.glPushMatrix();
 gl.glTranslatef(imageOffSetX, 0, 0);
 gl.glColor4f(1,1,1,1);
 gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
 gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

 gl.glVertexPointer(3, GL10.GL_FLOAT, 0,vertexBGBuffer);
 gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBGBuffer);
 gl.glDrawElements(GL10.GL_TRIANGLES, indices.length,GL10.GL_UNSIGNED_SHORT, indexBuffer);

 gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
 gl.glDisable(GL10.GL_TEXTURE_2D);

Then I draw a square onto my background image:

 gl.glPushMatrix();
 gl.glTranslatef(x, y, 0);
 gl.glColor4f(color[0], color[1], color[2], 1.0f); // Set to 1.0f temporarily
 gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
 gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
 gl.glDrawElements(GL10.GL_TRIANGLES, indices.length, GL10.GL_UNSIGNED_SHORT, indexBuffer);
 gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
 gl.glPopMatrix();

I've tried different values in the glBlendFunc but cannot understand how to achieve what I want. Any help is much appreciated :)

Upvotes: 0

Views: 4207

Answers (2)

Andrew White
Andrew White

Reputation: 53516

My answer may evolve but one thing I know for sure is that you should be using the following blend func...

gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);

Upvotes: 3

stealthcopter
stealthcopter

Reputation: 14206

I just found the solution, for the background texture to be drawn correctly I needed this:

   gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE);  

Then before drawing the square I needed to call this:

   gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);  

Upvotes: 2

Related Questions