2012-10-17 57 views
2

我無法實現以下行爲。我想從底部調整窗口大小,而不會渲染渲染場景或改變其位置。調整GLUT窗口的大小而不調整內容大小?

enter image description here

我使用C++的OpenGL GLUT

void resize(int w, int h) 
{ 
    float ratio = G_WIDTH/G_HEIGHT; 
    glViewport(0, 0, (h-(w/ratio))>0? w:(int)(h*ratio), (w-(h*ratio))>0? h:(int)(w/ratio)); 
} 
+1

請勿使用過量。沒有它,這是微不足道的 - 只需設置最大的視口大小,並且不要超過這個大小。 –

+0

你需要更新視口和投影矩陣,查看我的答案。 –

回答

1
ratio = wantedWidth/wantedHeight 
glViewport(0, 0, 
     (height-(width/ratio))>0? width:(int)(height*ratio), 
    (width-(height*ratio))>0? height:(int)(width/ratio); 

會做到這一點,它使比值始終窗口的高度/寬度之間的相同,同時還嘗試使用可用窗口的最大尺寸。

編輯:把它總是左上角。

+0

很接近!它做了效果,但爲了水平調整大小。 – Jonas

+0

你的意思是上面的代碼在垂直調整大小時不能正確調整大小,但是水平地很好? – SinisterMJ

+0

是的,就是這樣。 – Jonas

3

在GLUT調整大小場景函數中,默認情況下視口可能設置爲窗口大小。我會嘗試只是改變這是你想要的(固定)大小:

相反的:

void windowReshapeFunc(GLint newWidth, GLint newHeight) 
{ 
    glViewport(0, 0, newWidth, newHeight); 
    .. etc... 
} 

這樣做:

void windowReshapeFunc(GLint newWidth, GLint newHeight) 
{ 
    glViewport(0, 0, 400, 600); 
    .. etc... 
} 

或者任何大小你想要的。該窗口仍將調整大小,但這些場景將始終呈現給(現在固定的)視口。

2

如果使用的是正交透視使用這樣的:

#include <GL/glut.h> 

int x0, y0 = 0; 
int ww, hh = 0; 

void updateCamera() 
{ 
    glMatrixMode(GL_PROJECTION); 
    glLoadIdentity(); 
    glOrtho(x0, x0+ww, y0, y0+hh, -1, 1); 
    glScalef(1, -1, 1); 
    glTranslatef(0, -hh, 0); 
} 

void reshape(int w, int h) 
{ 
    ww = w; 
    hh = h; 
    glViewport(0, 0, w, h); 
    updateCamera(); 
} 

void display(void) 
{ 
    glClear(GL_COLOR_BUFFER_BIT); 
    glBegin(GL_TRIANGLES); 
    glColor3f(0.0, 0.0, 1.0); glVertex2i(0, 0); 
    glColor3f(0.0, 1.0, 0.0); glVertex2i(200, 200); 
    glColor3f(1.0, 0.0, 0.0); glVertex2i(20, 200); 
    glEnd(); 
    glFlush(); 
    glutPostRedisplay(); 
} 

int mx = 0; 
int my = 0; 
int dragContent = 0; 

void press(int button, int state, int x, int y) 
{ 
    mx = x; 
    my = y; 
    dragContent = button == GLUT_LEFT_BUTTON && state == GLUT_DOWN; 
} 

void move(int x, int y) 
{ 
    if(dragContent) 
    { 
     x0 -= x - mx; 
     y0 += y - my; 
     mx = x; 
     my = y; 
     updateCamera(); 
    } 
} 

int main(int argc, char **argv) 
{ 
    glutInit(&argc, argv); 
    glutCreateWindow("Resize window without resizing content + drag content"); 
    glutDisplayFunc(display); 
    glutReshapeFunc(reshape); 
    glutMouseFunc(press); 
    glutMotionFunc(move); 
    glutMainLoop(); 
    return 0; 
} 

可以使用左鼠標拖動內容(三角形)。

+0

我可以使用Glut甚至WIN API來防止水平調整大小嗎? – Jonas

+0

不確定爲什麼你需要窗口具有固定的寬度。但我想用WIN API,可以在窗口大小調整時設置窗口寬度。 –

1

下面是我找到的解決方案,我認爲它工作得很好。

我寫我的重塑方法如下,這與glutReshapeFunc(reshape)在我的主要方法進行註冊:

void reshape(int width, int height) { 
    glViewport(0, 0, width, height); 
    aspect = ((double) width)/height; 

每當我重新繪製的場景,我使用這個調用來設置相機:

glMatrixMode(GL_PROJECTION); 
glLoadIdentity(); 
gluPerspective(45.0, aspect, 1.0, 100.0); // 45 degrees fovY, correct aspect ratio 
// then remember to switch back to GL_MODELVIEW and call glLoadIdentity 

這讓我把窗口當作一個窗口進入我的場景,而不用縮放或移動場景。我希望這是你正在尋找的!