c++ - 在 OpenGL 中用鼠标绘制多条线

标签 c++ opengl

我试图在我的 OpenGL 和 C++ 程序中用我的鼠标绘制多条线段。现在我可以画一个,一旦我开始画另一个,前一个就消失了。

下面是我的与鼠标绘图相关的代码。关于如何绘制多条线有什么建议吗?

LineSegment seg;

void mouse(int button, int state, int x, int y) {

    if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {                 // if left button is clicked, that is the start point
        seg.x1 = seg.x2 = x;
        seg.y1 = seg.y2 = y;
    }

    if (button == GLUT_LEFT_BUTTON && state == GLUT_UP) {                   // once they lift the mouse, thats the finish point
        seg.x2 = x;
        seg.y2 = y;
    }

}

void motion(int x, int y) {
    seg.x2 = x;
    seg.y2 = y;

    glutPostRedisplay();                                                    // refresh the screen showing the motion of the line
}

void display(void) {
    glClear(GL_COLOR_BUFFER_BIT);                                           // clear the screen

    glBegin(GL_LINES);                                                          // draw lines
    glVertex2f(seg.x1, seg.y1);
    glVertex2f(seg.x2, seg.y2);

    glEnd();

    glutSwapBuffers();
}

最佳答案

void display(void) {
    glClear(GL_COLOR_BUFFER_BIT);                                           // clear the screen

    glBegin(GL_LINES);                                                          // draw lines
    glVertex2f(seg.x1, seg.y1);
    glVertex2f(seg.x2, seg.y2);

    glEnd();

    glutSwapBuffers();
}

您需要将之前的线段保存在数据结构中,并在您用鼠标单击时添加到其中。然后 drawloop 需要遍历该数据结构并绘制每个保存的线段。

std::vector<LineSegment> segmentvector;
//Each time you release the mouse button, add the current line segment to this vector
/*...*/

glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_LINES);
for(const LineSegment & seg : segmentvector) {
    glVertex2f(seg.x1, seg.y1);
    glVertex2f(seg.x2, seg.y2);
}

glVertex2f(currseg.x1, currseg.y1);
glVertex2f(currseg.x2, currseg.y2);
glEnd();

我还强烈建议您在学习 OpenGL 时不要使用 Fixed-Function-Pipeline 函数。 There are lots of tutorials online for learning modern OpenGL.

关于c++ - 在 OpenGL 中用鼠标绘制多条线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33572001/

相关文章:

c++ - 是否可以在 "reserved"cpu 内核上运行代码?

C++ - Tesseract 令人失望的性能

c++ - Juno CDT 插件无法运行 C++ 应用程序

c++ - 使用多个 Canvas 时,FTGL 纹理字体仅显示黑框

opengl - 使用 2 个摄像头进行头部姿势估计

c++ - 如何在C++类中计算成员偏移

c++ - 如何找到给定范围内除以给定数字时具有一定余数的值的个数?

Qt OpenGL 动态与桌面

c++ - 如何在 VBO 中使用步幅参数?

java - 在 OpenGL 中使用 GL_QUADS 渲染时,形状的一部分丢失