search

Home  >  Q&A  >  body text

c++ - OpenGL 如何绘制一段颜色渐变的直线

比如

glBegin( GL_LINE_STRIP );
    for(int i=0; i<n; ++i){
        /**
            if( i 满足某条件 )
                glColor3f( 设置为某颜色 );
            else if(///)
                glColor3f(///);
            ...
            这么写似乎不可以
        */
        glVertexf( /*vertex i*/ );
    }
glEnd();
ringa_leeringa_lee2803 days ago926

reply all(3)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:06:29

    glBegin( GL_LINE_STRIP );
        glColor3f( 设置为起点颜色 );
        glVertex3f( 起点);
        glColor3f(设置为终点颜色);
        glVertex3f( 终点);
    glEnd();
    

    It’s that simple. What the hell is handwritten software rendering? Why use opengl when the interpolation is already handwritten?

    Remember, opengl’s default color gradient method is the simplest linear interpolation. Any primitive with different vertex colors will have a gradient inside.

    If you don’t want to use simple linear interpolation, you can use Shader. You can calculate the color you should have based on the interpolated color in the fragment shader. For details on how to use Shader and modern OpenGL features, please read the latest version of OpenGL Programming Guide.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:06:29

    glShadeModel(GL_SMOOTH);
    Have you written this sentence? If so, you only need to set the colors of the two endpoints of the straight line, and OpenGL will draw the gradient color for you by default;

    But looking at your code, it seems that you want to draw a series of points and set the color of each point based on some conditions? It is recommended that the problem description be more detailed and include all the code.

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 13:06:29

    Write a general Bresenham algorithm for you first

    void BresenHam(int x1, int y1, int x2, int y2)
    {
        int x = x1;
        int y = y1;
        int dx = abs(x2 - x1);
        int dy = abs(y2 - y1);
        int s1 = sign(x2 - x1);
        int s2 = sign(y2 - y1);
        int interchange = 0;
        if (dy > dx)
        {
            int temp = dx;
            dx = dy;
            dy = temp;
            interchange = 1;
        }
        else
        {
            interchange = 0;
        }
        int e = 2 * dy - dx;
        for (int i = 1;i <= dx;i++)
        {
            //画点 (x,y)
            while (e > 0)
            {
                if (interchange == 1)
                    x = x + s1;
                else
                    y = y + s2;
                e = e - 2 * dx;
            }
            if (interchange == 1)
                y = y + s2;
            else
                x = x + s1;
            e = e + 2 * dy;
        }
    }

    Let’s draw dots one by one. This is what I think. Just write a function to change the values ​​of the R G B components. .

    reply
    0
  • Cancelreply