2012-09-20 77 views
0

我在調整GLUT窗口大小時遇到​​問題。我想打印一個矩形,但是當我使用調整大小功能,我似乎無法在窗口中繪製和形狀。我有下面的代碼,我想改變廣場的寬度,當我調整窗口大小,但如果高度被調整大小,我不希望它的高度改變。在OpenGL中更改投影

#include <GLUT/glut.h> 
#include <stdio.h> 
#include <stdlib.h> 
/* globals */ 
GLsizei wh = 500, ww = 500; 
/* initial window size */ 
GLfloat size = 3.0; 
/* half side length of square */ 

void myinit(void) 
{ 
    glClearColor(0.0,0.0,1.0,1.0); 
    glMatrixMode(GL_PROJECTION); 
    glLoadIdentity(); 
    glOrtho(0,1,0,1.0,-1.0,1.0); 
    glViewport(0,0,ww,wh); 
} 

/* display callback -- required by GLUT 3.0 */ 
void renderScene(void) 
{ 
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 
    glColor3f(1.0,.5,.7); 
    glBegin(GL_POLYGON); 
     glVertex3f (0.25, 0.25, 0.0); 
     glVertex3f (0.75, 0.25, 0.0); 
     glVertex3f (0.75, 0.75, 0.0); 
     glVertex3f (0.25, 0.75, 0.0); 
    glEnd(); 

    glFlush(); 
} 

void mouse(int button, int state, int x, int y) { 
    if(button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) { 
     glMatrixMode(GL_PROJECTION); 
     glLoadIdentity(); 
     glOrtho(0.0,500,0.0,500,0.0,1.0); 
    } 
} 
/*app quits if q is pressed*/ 
void keyboard(unsigned char key, int x, int y) { 
    if(key == 'Q' | key == 'q') 
     exit(0); 
} 

/* The main program -- note that there is no "flow of control" -- the program merely calls   functions to handle interactions */ 
int main(int argc, char** argv) 
{ 
    glutInit(&argc, argv); 
    glutInitWindowSize(ww,wh); 
    glutInitWindowPosition(100,100); 
    glutCreateWindow("Square"); 

    myinit(); 

    glutMouseFunc(mouse); 
    glutKeyboardFunc(keyboard); 
    glutDisplayFunc(renderScene); 
    //glutReshapeFunc(changeSize); 
    glutMainLoop(); 
    return 0; 
} 

我做了一個試驗changeSize功能,當我用它只會顯示一個空的藍色窗口,而不矩形在那裏

回答

3

你的問題在於使用了正交矩陣固定值:

glOrtho(0.0,500,0.0,500,0.0,1.0);

它說的是,但我的大窗口,使0映射到窗口的底部,並500映射到窗口的頂部頂點位置。

所以,如果你有一個500像素的高窗口,並且你畫一個能夠覆蓋100個單位的正方形,這將在窗口中映射到100個像素。

但是,如果您將窗口拉伸至1000像素高,現在您將一個從0至500的區域映射到高度爲1000像素的窗口。因此,您現在用於覆蓋100像素高度的相同方塊現在可以覆蓋200像素的高度。

如果您希望在調整大小時始終保持相同大小,則需要更新正交矩陣以將較大區域映射到新的較大窗口。因此,如果您更改正交矩陣以將區域0 to windowHeight映射到窗口,則100個正方形將始終填充完全相同的高度。

glOrtho(0.0, //left 
     500, //right 
     0.0, //bottom 
     height_in_pixels, //top 
     0.0, //near 
     1.0); //far