在OpenGL中设置透明背景颜色不起作用

时间:2018-02-08 00:18:41

标签: c linux opengl glut blending

我尝试使用函数 - glClearColor()和glClear()将背景颜色设置为透明颜色。但是,传递给glClearColor()的alpha值根本不会改变任何东西。

以下是我尝试运行的代码:

 #include<GL/glut.h>

    void display()
    {
        glClear(GL_COLOR_BUFFER_BIT);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        gluOrtho2D(0.0,(float)glutGet(GLUT_WINDOW_WIDTH),0.0,(float)glutGet(GLUT_WINDOW_HEIGHT));

        glBegin(GL_LINES);
            glVertex2i(200,200);
            glVertex2i(300,305);
        glEnd();

        glFlush();
    }

    int main(int argc, char *argv[const])
    {
        glutInit(&argc, argv);
        glutInitDisplayMode(GLUT_RGBA | GLUT_ALPHA);
        glutInitWindowSize(1100,620);
        glutInitWindowPosition((glutGet(GLUT_SCREEN_WIDTH)-1100)/2,(glutGet(GLUT_SCREEN_HEIGHT)-620)/2);
        glutCreateWindow("GLUT Programming");
        glClearColor(0.0f,0.0f,0.0f,0.5f);   // I have tried experimenting with this part, but, nothing happens
        glutDisplayFunc(display);
        glutMainLoop();
    }

我在运行Fedora 26的机器上使用freeglut和freeglut-devel,如果有帮助的话。

编辑:

结果我得到了:

The background color is black and fully opaque

结果我想获得:

The background is transparent and the window underneath is visible

1 个答案:

答案 0 :(得分:1)

如果您要启用Blending,则必须启用混合(glEnable( GL_BLEND )),然后必须设置混合功能(glBlendFunc)。
此外,您必须设置颜色的Alpha通道,用于绘制几何图形(glColor4f

以某种方式改变你的代码:

glClearColor( 0.5f, 0.5f, 0.5f, 1.0f );              // background color
glClear(GL_COLOR_BUFFER_BIT);                        // clear background with background color

glEnable( GL_BLEND );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); // = color * alpha + background * (1-alpha)
glColor4f( 1.0f, 0.0f, 0.0f, 0.1f );                 // color of the line, alpha channel 0.1 (very "transparent")
glLineWidth( 5.0 );

glBegin(GL_LINES);
.....