OpenGL - 如何使用弹出菜单绘制多个不同的 2D 形状?
Posted
技术标签:
【中文标题】OpenGL - 如何使用弹出菜单绘制多个不同的 2D 形状?【英文标题】:OpenGL - How to draw multiple different 2D shapes using pop-up menu? 【发布时间】:2015-03-15 18:20:59 【问题描述】:我正在尝试制作一个简单的 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】:您需要使用 glBegin(GL_LINES) 而不是 glBegin(GL_LINE)。
GL_LINE 是无关函数 glPolygonMode 的参数。
【讨论】:
以上是关于OpenGL - 如何使用弹出菜单绘制多个不同的 2D 形状?的主要内容,如果未能解决你的问题,请参考以下文章
如何优化多个全屏透明 iPhone OpenGL ES 图层的绘制?