OpenGL: Rotate, Scale and Translate

In my previous post, OpenGL ES Wrapper- Your First Application, you would have seen that we were creating a GlyphRun that we then draw. This is actually a wrapper class that handles all the processing required to draw the text on the screen. However, it doesn’t handle the positioning of the text on the screen – by default it is located at the origin ie (0,0,0).

To move this text around the screen we can specify an amount to translate, scale or even rotate the text by using the appropriate OpenGL commands. One thing to note here is that the order in which you do these operations may change the result you see. For example in the following images the original text (first image) is translated by (50,50,0) and then rotate around the z axis by 40 degrees.

image

Now apply translation and rotation – note the order of the gl.Translate and gl.Rotate method calls.

gl.Translatef(50.0f,50.0f,0);
gl.Rotatef(40.0f,0,0,1.0f);
title.Draw();

 image 

Now apply translation and rotation in the other order.

gl.Rotatef(40.0f,0,0,1.0f);
gl.Translatef(50.0f,50.0f,0);
title.Draw();

image

You can see that the order that rotate and translate are applied makes a difference. Interestingly they almost appear in the wrong order. In the second image the original image has been translated by (50,50,0) then rotated to get the text to where it appears, whilst in the previous image the text has been rotated by 40 and then translated. This is a result of the way OpenGL uses matrix multiplication to apply transforms to what you are drawing. Each time you issue a transform the corresponding matrix is multiplied against the current matrix to calculate the position of the items you drawing.

The other thing you’ll notice is that the text appears to be rotating around the top left corner of the text. To get it to rotate around the centre of the text, you need to apply a translate function to position the text with its centre at the origin, prior to rotating it and then translating it back into it’s final position.

image image image

Update – here’s the code for doing this additional translation (again, note the order that they’re done in)

gl.Translatef(50.0f, 50.0f, 0);
gl.Rotatef(40.0f, 0, 0, 1.0f);
gl.Translatef(-title.Size.Width/2, -title.Size.Height/2, 0);
title.Draw();

Leave a comment