OpenGL - 如何使用弹出菜单绘制多个不同的2D形状?

时间:2015-03-15 18:20:59

标签: opengl 2d glut freeglut

我试图创建一个简单的openGL应用程序,使用鼠标点击创建形状。使用使用鼠标右键打开的弹出菜单选择所需的形状。目前我有矩形工作,还有一个简单的绘画功能使用点。它们一旦重新绘制就会消失,但这是我将来担心的一个问题。

目前我还尝试将Line功能实现为菜单选项。我有以下代码,但是当我从弹出菜单中选择Line选项并单击两个点时,它似乎没有按预期绘制一条线。任何人都可以指出我在哪里出错吗?

GLfloat x1, x2, y1, y2;
GLfloat x_Src, y_Src, x_Dest, y_Dest;

//used to change colour (To be implemented)
static int colour;

void menu(int);

void display(void)
{
glClearColor(0.0, 2.0, 1.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);

glPointSize(3.0);
glColor3f(1.0, 0.0, 0.0);

//Rectangle vertices
glBegin(GL_POLYGON);
glVertex2f(x1, y1);
glVertex2f(x1, y2);
glVertex2f(x2, y2);
glVertex2f(x2, y1);
glEnd();

//Line vertices
glColor3f(0.0, 0.0, 1.0);
glBegin(GL_LINE);
glVertex2f(x_Src, y_Src);
glVertex2f(x_Dest, y_Dest);
glEnd();

glFlush();
return;
}

void MyRect(GLint button, GLint state, GLint x, GLint y)
{
static int first = 1;

if (state == GLUT_DOWN && button == GLUT_LEFT_BUTTON)
{
    if (first)
    {
        //first point in terms of window size
        x1 = (x - 250.0) / 250.0;
        y1 = -(y - 250) / 250.0;;
    }
    else
    {
        //second point in terms of window size
        x2 = (x - 250.0) / 250.0;
        y2 = -(y - 250) / 250.0;
        glutPostRedisplay();
    }
    first = !first;
}

return;
}


void MyLine(GLint button, GLint state, GLint x, GLint y)
{
static int first = 1;

if (state == GLUT_DOWN && button == GLUT_LEFT_BUTTON)
{
    if (first)
    {
        x_Src = (x - 250.0) / 250.0;
        y_Src = -(y - 250) / 250.0;

    }
    else
    {
        x_Dest = (x - 250.0) / 250.0;
        y_Dest = -(y - 250) / 250.0;
        glutPostRedisplay();
    }
    first = !first;
}
return;
}

//allows drawing of un-fixed line using mouse
void MyPaint(GLint x, GLint y)
{
    glColor3f(0.0, 0.0, 0.0);
    glPointSize(3.0);
    glBegin(GL_POINTS);
    glVertex2f((x - 250.0) / 250.0, -(y - 250.0) / 250.0);
    glEnd();

    glFlush();
    return;
}

void MainMenu(int item)
{
//Remove motion function if exists and go to rectangle function
//prevents two functions running at once
if (item == 1)
{
    glutMotionFunc(NULL);
    glutMouseFunc(MyRect);
}
else if (item == 2)
{
    glutMotionFunc(NULL);
    glutMouseFunc(MyLine);
}
else if (item == 5)
{
    glutMouseFunc(NULL);
    glutMotionFunc(MyPaint);
}
glutPostRedisplay();
return;
}


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

glutInit(&argc, argv);
glutInitWindowSize(500, 500);
glutInitWindowPosition(500, 200);
glutCreateWindow("Draw Shapes");
glutDisplayFunc(display);

glutCreateMenu(MainMenu);
glutAddMenuEntry("Rectangle", 1);
glutAddMenuEntry("Line", 2);
glutAddMenuEntry("Circle", 3);
glutAddMenuEntry("Triangle", 4);
glutAddMenuEntry("Paintbrush", 5);
glutAddMenuEntry("Background colour", 6);
glutAddMenuEntry("Clear screen", 7);
glutAttachMenu(GLUT_RIGHT_BUTTON);

glutMainLoop();
}

1 个答案:

答案 0 :(得分:0)

您需要使用glBegin(GL_LINES)而不是glBegin(GL_LINE)。

GL_LINE是无关函数glPolygonMode的参数。

相关问题