How to set top opacity in OpenGL?

The following fragment draws a gray square.

glColor3b(50, 50, 50);

glBegin(GL_QUADS);
glVertex3f(-1.0, +1.0, 0.0); // top left
glVertex3f(-1.0, -1.0, 0.0); // bottom left
glVertex3f(+1.0, -1.0, 0.0); // bottom right
glVertex3f(+1.0, +1.0, 0.0); // top right
glEnd();

In my application, there is a colored cube behind this single square.

What function should be used to make a square (and only this square) opaque?

+5
source share
4 answers

In the init function, use the following two lines:

glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

And in your rendering function, make sure that it is glColor4fused instead glColor3f, and set the 4th argument to the desired opacity level.

glColor4f(1.0, 1.0, 1.0, 0.5);

glBegin(GL_QUADS);
glVertex3f(-1.0, +1.0, 0.0); // top left
glVertex3f(-1.0, -1.0, 0.0); // bottom left
glVertex3f(+1.0, -1.0, 0.0); // bottom right
glVertex3f(+1.0, +1.0, 0.0); // top right
glEnd();
+10
source

glColor4f (float r, float g, float b, flaot alpha);
( clColor4b)
, .
( reset --, glGet * )

+2

Use glColor4instead glColor3. For example:

glBlendFunc(GL_SRC_ALPHA,GL_ONE);
glColor4f(1.0f,1.0f,1.0f,0.5f);
+2
source

You can set the colors to the top.

glBegin(GL_QUADS);
glColor4f(1.0, 0.0, 0.0, 0.5); // red, 50% alpha
glVertex3f(-1.0, +1.0, 0.0); // top left
// Make sure to set the color back since the color state persists
glVertex3f(-1.0, -1.0, 0.0); // bottom left
glVertex3f(+1.0, -1.0, 0.0); // bottom right
glVertex3f(+1.0, +1.0, 0.0); // top right
glEnd();
+2
source

All Articles