博客转自:https://www.cnblogs.com/yangxi/archive/2011/09/16/2178507.html
前一章我们知道了怎么建立简单的菜单,现在我们来看看怎样来添加一个级联的子菜单。子菜单的建立和我们前面用的建立菜单的函数一样。建立菜单后我们把子菜单作为一个条目添加进去。使用函数glutAddSubMenu来完成这项工作:
void glutAddSubMenu(char *entryName,int menuIndex); 参数: entryName:子菜单名称。 menuIndex:子菜单索引,这个就是我们调用glutCreateMenu来创建子菜单返回的值。
上面就是添加子菜单的函数。下面是一小段代码,说明上面函数的用处的。
void createGLUTMenus() { int menu,submenu; submenu = glutCreateMenu(processMenuEvents); glutAddMenuEntry("Red",RED); glutAddMenuEntry("Blue",BLUE); glutAddMenuEntry("Green",GREEN); menu = glutCreateMenu(processMenuEvents); glutAddMenuEntry("White",WHITE); glutAddSubMenu("RGB Menu",submenu); glutAttachMenu(GLUT_RIGHT_BUTTON); }
注意这里处理菜单事件的函数,对菜单和子菜单都是一样的,你可以自己写个处理子菜单事件的函数。完整代码如下
#include <gl/glut.h> #define RED 1 #define GREEN 2 #define BLUE 3 #define WHITE 4 //所有的变量被初始化为1,表明三角形最开始是白色的。 float red = 1.0, blue = 1.0, green = 1.0; static float angle = 0.0, angleX = 0.0, ratio; // initially define the increase of the angle by 0.05; float deltaAngle = 0.05; void renderScene(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glPushMatrix(); glRotatef(angle, 0.0, 1.0, 0.0); glRotatef(angleX, 1.0, 0.0, 0.0); glColor3f(red, green, blue); glBegin(GL_TRIANGLES); glVertex3f(-0.5, -0.5, 0.0); glVertex3f(0.5, 0.0, 0.0); glVertex3f(0.0, 0.5, 0.0); glEnd(); glPopMatrix(); // this is the new line // previously it was: angle++; angle += deltaAngle; glutSwapBuffers(); } void reShape(int w, int h) { // 防止被0除. if (h == 0) h = 1; ratio = 1.0f * w / h; //Reset the coordinate system before modifying glMatrixMode(GL_PROJECTION); glLoadIdentity(); //设置视口为整个窗口大小 glViewport(0, 0, w, h); //设置可视空间 gluPerspective(45, ratio, 1, 1000); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0.0, 0.0, 5.0, 0.0, 0.0, -1.0, 0.0f, 1.0f, 0.0f); } void processMenuEvents(int option) { //option,就是传递过来的value的值。 switch (option) { case RED: red = 1.0; green = 0.0; blue = 0.0; break; case GREEN: red = 0.0; green = 1.0; blue = 0.0; break; case BLUE: red = 0.0; green = 0.0; blue = 1.0; break; case WHITE: red = 1.0; green = 1.0; blue = 1.0; break; } } void createGLUTMenus() { int menu, submenu; submenu = glutCreateMenu(processMenuEvents); glutAddMenuEntry("Red", RED); glutAddMenuEntry("Blue", BLUE); glutAddMenuEntry("Green", GREEN); menu = glutCreateMenu(processMenuEvents); glutAddMenuEntry("White", WHITE); glutAddSubMenu("RGB Menu", submenu); glutAttachMenu(GLUT_RIGHT_BUTTON); } void main(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); glutInitWindowPosition(100, 100); glutInitWindowSize(320, 320); glutCreateWindow("GLUT Tutorial Menu"); glutDisplayFunc(renderScene); glutIdleFunc(renderScene); glutReshapeFunc(reShape); //调用我们的函数来创建菜单 createGLUTMenus(); glutMainLoop(); }
显示效果如下