问题
I have a 3d scene drawn by OpenGL to a resizeable window. Now, when the window gets resized, I do not want to scale the viewport, rather I want to keep the scene at a fixed size and show a larger portion of it (or crop the scene image). This is my current code:
GLfloat ratio;
// Protect against a divide by zero
if ( height == 0 )
height = 1;
ratio = ( GLfloat )width / ( GLfloat )height;
// Setup our viewport.
glViewport( 0, 0, ( GLint )width, ( GLint )height );
// change to the projection matrix and set our viewing volume.
glMatrixMode( GL_PROJECTION );
glLoadIdentity( );
gluPerspective( 60.0f, ratio, 0.1f, 1000.0f );
// Switch back to the modelview
glMatrixMode( GL_MODELVIEW );
If I keep the ratio fixed, then the scene image simply gets scaled, but I want to keep it at fixed size and simply show a wider view. Any ideas on this?
回答1:
Adjust the fov parameters. Technically what you want to do is easier if done using glFrustum instead of gluPerspective.
// Protect against a divide by zero
if ( height == 0 )
height = 1;
// Setup our viewport.
glViewport( 0, 0, ( GLint )width, ( GLint )height );
// change to the projection matrix and set our viewing volume.
glMatrixMode( GL_PROJECTION );
glLoadIdentity( );
// supply some sensefull value for this; ideally let the user adjust it somehow
exterm float Zoom;
// near far should tightly wrap the actually visible set of objects. Hardcoded values
// like 0.1 ... 1000.f are problematic. Also your choosen value range slices your viewport
// into 10000 depth slices. Say you get only a 16 bit depth buffer already in the lineary
// slicing ortho projection a OpenGL length units in depth would recieve only about 6
// slices. In perspective mode the slice density follows a 1/depth law. So already at depth
// 10 you'll run into depth resolution problems.
glFrustum(-Zoom * width, Zoom * width, -Zoom * height, Zoom * height, near, far);
// Switch back to the modelview
glMatrixMode( GL_MODELVIEW );
Take note that this code belongs into the display function. Any tutorial that sets viewport and projection in a window reshape handler is very bad style; don't follow it.
回答2:
Ideally, since you have set the viewport to 0,0,width,height, the image should remain in the same size. Can you check the coordinates you send for the image. Does that remain constant or does it scale along with width/ height? Can you post the code for adding vertices.
来源:https://stackoverflow.com/questions/5894866/resize-viewport-crop-scene