2

所以我试图在窗口内绘制一条锯齿线,它通过鼠标点击获取它的 x 和 y 坐标。所以每次点击窗口后,最后两个顶点都会连接在一起,依此类推。

#include <iostream>
#include <GL/glut.h>

void init(){
    glClearColor(1.0, 1.0, 1.0, 1.0);
    glViewport(0, 0, 800, 400);
    gluOrtho2D(0.0, 800.0, 0.0, 400.0);
}

int x1, y1, x2, y2, count = -1;

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

    if(key == GLUT_LEFT_BUTTON){
      if(state == GLUT_DOWN){
        count++;
        if(count%2 == 0){
            x1 = x;
            y1 = 400.0-y;
        }
        else{
            x2 = x;
            y2 = 400.0-y;
            glutPostRedisplay();
        }
      }
    }
}

void Display(){

    glClear(GL_COLOR_BUFFER_BIT);
    glColor3i(1, 1, 1);

    if(count != 0){

        glBegin(GL_LINE_STRIP);

            glVertex2i(x1, y1);
            glVertex2i(x2, y2);

        glEnd();
    }
    glFlush();
}

int main(int argc, char* argv[]) {

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
    glutInitWindowSize(800, 400);
    glutCreateWindow("Vije e thyer");
    init();
    glutMouseFunc(mouse);
    glutDisplayFunc(Display);
    glutMainLoop();
    return 0;
}

我希望它显示在窗口上绘制的每一行,但是一旦创建了新行,最后一行就会消失。我认为这是 glutPostRedisplay 的问题。

4

1 回答 1

2

All your old lines disappear because you call glClear, which clears your screen. Calling glClear every frame is a good idea, but now after calling glClear, you only draw a single line segment between the last two points you clicked on.

What you could do to make it work is just skip the call to glClear, but that's really not the way OpenGL is intended to be used, and it's not flexible at all (what if you want to make the lines wiggle a bit, or change color?). Additionally it is error-prone, especially with double-buffering. Suppose you click twice on consecutive frames. One of your line segments only ever gets drawn in one frame, so it is only ever drawn to one of the two buffers. This will make your segment appear to flicker on your screen. Or if you change your window size, you'll definitely lose some of the information in your screen buffers (if not the entire buffer contents).

What you need to do is keep track of all the points you want to draw, in a list or something, then redraw the entire zig-zag line each frame.

于 2019-06-05T12:40:24.077 回答