Thursday 21 June 2012

Rotating an image in opengl


In this part we will take a look on how to rotate an image in its local coordinates.

To rate an image opengl provides us with a function
glRotatef(angle,x,y,z);

angle indicates the rotation angle in degrees.
x,y,z indicates along which axis the image should rotate.

For example,
glRotatef(30,1,0,0)  would rotate an image in 30 degrees angle along x-axis.
glRotatef(90,0,1,0)  would rotate an image in 90 degrees angle along y-axis.
glRotatef(180,0,0,1)  would rotate an image in 180 degrees angle along z-axis.

But, it’s not sufficient to rotate an image just by passing the angle and specifying the coordinate axis. We have certain steps to be followed.


Steps to be followed:


The fact is that the image rotates w.r.t screen coordinates if we only use the above function, but the actual rotation we want is w.r.t image local coordinates.

Example of screen co-ordinates and local co-ordinates are shown below:


Now, how do we do that? Here it is

Step 1: Translate the image to screen coordinates
Step 2: Rotate the image to the desired angle and specify the axis.
Step 3: Finally, translate the image back to its original coordinates.

Let’s consider an example. Assume we have an image at rendered 10 , 10 (x, y coordinates)and you want to rotate the image in 30 degrees along z- axis.

Our normal image without rotation would something look like figure below :


Firstly ,Calculate the centerx and centery of the image
centerx = 10 + imagewidth/2;
centery = 10 + imageheight/2

Step 1:
Translate the image to screen coordinates

                                     glTranslatef(-centerx,-centery,0.0f);


Step 2:
Rotate the image to 30 degrees along z- axis



                                     glRotatef(30, 0.0f, 0.0f, 1.0f);


Step 3:
Translate back to its local coordinates

                                    


                                      glTranslatef(centerx, centery, 0.0f);

That’s it your done.

NOTE: The opengl takes the commands in the reverse way so while applying this in code it should be like this
glTranslatef(centerx,centery,0.0f);//final step
glRotatef(30, 0.0f, 0.0f, 1.0f);// 2nd step
glTranslatef(-centerx,centery,0.0f); //first step


You can download the complete source code here


No comments:

Post a Comment