How to scale a rectangle in Opengl keeping it at its initial position

155 Views Asked by At

I want to scale a rectangle in OpenGL using the scaling transformation matrix. The vertices of the rectangle are (325,320), (460,320), (460,150), and (325,150). I have defined a function to execute the transformation and kept the scaling factor as the parameter of the function. But when I call the function, the rectangle reduces in size but does not stay in its initial position. How can I scale it while keeping it in its original position?

Here's my code for scaling the rectangle:

def scaling(sc):


    s = np.array([[sc, 0, 0],
                  [0, sc, 0],
                  [0, 0, 1]])

    v1 = np.array([[325],
                   [320],
                   [1]])
    v2 = np.array([[460],
                   [320],
                   [1]])
    v3 = np.array([[460],
                   [150],
                   [1]])
    v4 = np.array([[325],
                   [150],
                   [1]])


    v11 = np.matmul(s, v1)
    v22 = np.matmul(s, v2)
    v33 = np.matmul(s, v3)
    v44 = np.matmul(s, v4)

    glColor3f(1.5, 0.17, 0)
    glBegin(GL_QUADS)
    glVertex2f(v11[0][0], v11[1][0])
    glVertex2f(v22[0][0], v22[1][0])
    glVertex2f(v33[0][0], v33[1][0])
    glVertex2f(v44[0][0], v44[1][0])
    glEnd()
1

There are 1 best solutions below

0
Rabbid76 On

You must scale the object before you move it. Center the object around (0, 0), scale it with glScale and move it to its position with glTranslate. Use glPushMatrix and glPopMatrix to save and restore the transformation matrix.

def scaling(sc):

    glPushMatrix()
    glTranslatef(392.5, 185, 0)
    glScalef(sc, sc, 1)

    glColor3f(1.5, 0.17, 0)
    glBegin(GL_QUADS)
    glVertex2f(-67.5, 35)
    glVertex2f(67.5, 35)
    glVertex2f(67.5, -35)
    glVertex2f(-67.5, -35)
    glEnd()

    glPopMatrix()

Note that this is the same as orienting the object around the point (0, 0) with glTranslate beforehand:

def scaling(sc):

    glPushMatrix()
    glTranslate(392.5, 185, 0)
    glScalef(sc, sc, 1)
    glTranslate(-392.5, -185, 0)

    glColor3f(1.5, 0.17, 0)
    glBegin(GL_QUADS)
    glVertex2f(325, 320)
    glVertex2f(460, 320)
    glVertex2f(460, 150)
    glVertex2f(325, 150)
    glEnd()

    glPopMatrix()