Home > Back-end >  OpenGL Try to draw square but its display a rectangle
OpenGL Try to draw square but its display a rectangle

Time:08-02

I try to draw a simple square by OpenGL but the result its display a rectangle. I guess that the problem is in the reshape function but I have no idea why (I'm new to OpenGL).

I what to keep aspect when I resize the window, that is not to stretch or shrink my image.

image screenshot

my reshape function

#define WINDOW_W 640
#define WINDOW_H 480

void reshape(int width, int height) {
    if (height == 0)
        height = 1;
    GLfloat aspect = (GLfloat)width / (GLfloat)height;

    glViewport(0, 0, (GLsizei)width, (GLsizei)height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    if (width >= height)
       gluOrtho2D(0.0f, (GLdouble)WINDOW_W * aspect, (GLdouble)WINDOW_H, 0.0f);
    else
       gluOrtho2D(0.0f, (GLdouble)WINDOW_W, (GLdouble)WINDOW_H / aspect, 0.0f);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

my draw function

void display(void) {
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    glLoadIdentity();

    // x=50 y=50 w=100 h=100 a square
    glBegin(GL_QUADS);
        glVertex2i(50, 50);
        glVertex2i(50, 150);
        glVertex2i(150, 150);
        glVertex2i(150, 50);
    glEnd();

    glutSwapBuffers();
}

CodePudding user response:

Right now, your "square" will always be exactly 1.3333 (640 / 480) times as tall as it is wide, because while you do take the actual window size into account and compute the actual aspect ratio given the actual window size, you multiply that with 640 for the width and 480 for the height, for whatever reason.

And that won't work since that will always stretch your actual aspect ratio by a factor of 1.3333 making your square always 1.3333 as tall as it is wide.

To solve this, just multiply the arguments to the gluOrtho2D() call with the same value, depending on what the extent in your world space or "view space" should be for a square view space with a square aspect ratio.

  • Related