OpenGL中的MyReshape函数不起作用

时间:2017-03-23 23:51:30

标签: c opengl window reshape

我试图在OpenGL中进行重塑功能来调整我的图形,但是当我调整窗口大小时,图形会变形,我不知道为什么。

代码如下:

void myReshape(int width, int height){
// Calculates the ratio
//
GLfloat ratio;

// We adjust viewport to new dimensions
//
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

// Checking dimensions
// Case 1: Width > Heigth
// Case 2: Height > Width
//
if (width > height)
{
    ratio = (GLfloat) width / (GLfloat) height;
    printf("Ratio1: %f\n", ratio);
    glOrtho(-ratio, ratio, -1.0f, 1.0f, 0.0f, 0.0f);
}
else
{
    ratio = (GLfloat) height / (GLfloat) width;
    printf("Ratio2: %f\n", ratio);
    glOrtho(-1.0f, 1.0f, -ratio, ratio, 0.0f, 0.0f);
}
glMatrixMode(GL_MODELVIEW);}

1 个答案:

答案 0 :(得分:1)

glOrtho(-dx,dx,-dy,dy,-dz,dz)定义了一个“框”,它由OpenGL内部调整以适合视口(宽度,高度)。这就是“dx”将适合“width”和“dy”到“height”。

如果您不想变形,只需要简单的比例,则必须遵守测量比率:ratio = width/height = dx/dy。所以,避免if-else基于比率
使用:

ratio = (GLFloat)width / height;
glOrtho(-ratio, ratio, -1.0f, 1.0f, 0.0f, 0.0f); //this near and far, better -1, 1

如果您不想在视口更改时调整图形大小,请使用与视口相同的距离:

GLfloat dx = (GLfloat)width / 2;
GLfloat dy = (GLfloat)heigth / 2;
glOrtho(-dx, dx, -dy, dy, -1, 1);
相关问题