从SharpGL中的文本输入中绘制线条

时间:2013-01-25 22:14:47

标签: c# opengl

我想在SharpGl中画线,但这段代码不起作用!

void Line_DDA(OpenGL gl,int X0, int Y0, int Xend, int Yend)
    {

        gl.LineWidth(2.5f);
        gl.Color(1.0, 0.0, 0.0);
        gl.Begin(OpenGL.GL_LINES);


        int dx = Xend - X0;
        int dy = Yend - Y0;
        int steps, k;
        float Xinc, Yinc;
        float x = X0;
        float y = Y0;

        if (Math.Abs(dx) > Math.Abs(dy))
            steps = Math.Abs(dx);
        else
            steps = Math.Abs(dy);

        float fdx = (float)dx;
        float fdy = (float)dy;
        float fsteps = (float)steps;
        Xinc = fdx / fsteps;
        Yinc = fdy / fsteps;

        gl.Vertex((int)x, (int)y);

        for (k = 0; k < steps; k++)
        {
            x += Xinc;
            y += Yinc;
            gl.Vertex((int)x, (int)y);
        }

        gl.End();

    }

当我使用

             gl.Vertex(10, 100);
             gl.Vertex(110, 110);

这是工作!

修改

这是我的代码中的调用块:

private void openGLControl_OpenGLDraw(object sender, PaintEventArgs e)
    {
        //  Get the OpenGL object.
        OpenGL gl = openGLControl.OpenGL;

        //  Clear the color and depth buffer.
        gl.Clear(OpenGL.GL_COLOR_BUFFER_BIT | OpenGL.GL_DEPTH_BUFFER_BIT);

        //  Load the identity matrix.
        gl.LoadIdentity();

        Line_DDA(gl, int.Parse(txtLineX1.Text), int.Parse(txtLineY1.Text), int.Parse(txtLineX2.Text), int.Parse(txtLineY2.Text));
        //drawLine(gl, 110, 120, 100, 100);
    }

为什么会这样?

1 个答案:

答案 0 :(得分:0)

使用GL_LINES绘制线条时,需要为每个线段提供2个顶点。相反,您的代码为每个线段提供单个顶点,就好像该线应该与前一个顶点连接。

实际上,解决方案是将绘制模式设置为GL_LINE_STRIP或为每个线段提供两个顶点。

然而,我不明白为什么你想要在需要两个点时绘制一条带有多个顶点的直线。