考虑这段代码:
#include <stdlib.h>
#include <stdarg.h>
#include <GLUT/GLUT.h>
#include <OpenGL/OpenGL.h>
double width=600;
double height=600;
void processMouse(int button, int state, int x, int y)
{
glColor4f(1.0,0.0,0.0,0.0);
glBegin(GL_POLYGON);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(1.0, 0.0, 0.0);
glVertex3f(1.0, 1.0, 0.0);
glVertex3f(0.0, 1.0, 0.0);
glEnd();
glFlush();
}
static void render()
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
glutMouseFunc(processMouse);
}
int main(int argc, char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(width, height);
glutCreateWindow("Board");
glutDisplayFunc(render);
glutMainLoop();
}
执行渲染函数,每次执行单击时,都应该启动函数processMouse。 因此,如果单击鼠标,所有窗口都应变为红色,并显示说明:
glColor4f(1.0,0.0,0.0,0.0);
glBegin(GL_POLYGON);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(1.0, 0.0, 0.0);
glVertex3f(1.0, 1.0, 0.0);
glVertex3f(0.0, 1.0, 0.0);
glEnd();
glFlush();
但是当我单击鼠标时,我注意到一个奇怪的行为:只有窗口的一部分被着色,即左下角的部分(而不是整个屏幕)。 窗口保持这种状态,直到我打开谷歌浏览器窗口。如果我打开谷歌浏览器(或其他图形应用程序),所有窗口都会变成红色。 为什么这个?我也有更复杂的程序的问题,似乎有时 glVertex 指令被忽略。如果我尝试使用 fprintf 调试程序,看起来一切正常,并且一切似乎都按预期进行(例如我尝试打印鼠标坐标在 processMouse 函数中,它们没问题),除了我绘制的内容被忽略。
编辑: 我修改了这段代码,但仍然存在同样的问题:
#include <stdlib.h>
#include <stdarg.h>
#include <GLUT/GLUT.h>
#include <OpenGL/OpenGL.h>
double width=600;
double height=600;
bool down=false;;
// http://elleestcrimi.me/2010/10/06/mouseevents-opengl/
static void render()
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
if(down)
{
glColor4f(1.0,0.0,0.0,0.0);
glBegin(GL_POLYGON);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(1.0, 0.0, 0.0);
glVertex3f(1.0, 1.0, 0.0);
glVertex3f(0.0, 1.0, 0.0);
glEnd();
glFlush();
}
}
void processMouse(int button, int state, int x, int y)
{
if(state==GLUT_DOWN)
{
down=true;
glutPostRedisplay();
}
}
int main(int argc, char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(width, height);
glutCreateWindow("Board");
glutMouseFunc(processMouse);
glutDisplayFunc(render);
glutMainLoop();
}
仍然只有屏幕的一部分变红。
PS:使用 glutSwapBuffers() 解决了,谢谢。
最佳答案
当您在 GLUT 下使用双缓冲时,您需要调用 glutSwapBuffers()
查看抽奖结果。
将此添加到 render()
的末尾功能并且它会正常工作。
关于c - 单击鼠标时绘制多边形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10082050/