27 May 2009

Author

Jan Vantomme

Categories

iPhone
Tutorial

OpenGL ES for iPhone: Drawing a Circle - Part III

In part 3 we’re going to take a look on how we can optimize the code to make our app run smoother. At this moment, all vertices of the circle are calculated each time the view gets drawn. This is a waste of computing power because the values of these vertices don’t change. It would be better if we calculate these values once when the program loads.

Add the folowing variables to the @interface section in EAGLView.h and remove them from the drawView method. By doing this the variables will be available to every method in the class.

GLfloat vertices[722];
GLfloat colors[1444];

Move the piece of code that calculates the vertices from drawView to initWithCoder.

vertices[0] = 0.0;
vertices[1] = 0.0;
for (int i = 0; i < 720; i += 2) {
    vertices[i+2]  = (cos(DEGREES_TO_RADIANS(i/2)) * 1);
    vertices[i+3] = (sin(DEGREES_TO_RADIANS(i/2)) * 1);
}
vertices[719] = 0.0;
vertices[720] = 1.0;

Scaling the circle

If you want to draw a bigger or smaller circle you don’t need to recalculate the vertices. You can scale the circle with the glScalef() method. This method takes three floats for x, y an z as arguments. Add this line of code before drawing the vertex array.

glScalef(0.7, 0.7, 1.0);
glDrawArrays(GL_TRIANGLE_FAN, 0, 361);

A circle with a size of 70% of the original circle will be drawn to the screen. There is a small problem though. The circle will scale 70% every time the drawView method gets called and the circle will disappear eventually. This problem can be solved by using the pushMatrix() and popMatrix() methods. Change the drawing code to this:

glPushMatrix();
glScalef(0.7, 0.7, 1.0);
glDrawArrays(GL_TRIANGLE_FAN, 0, 361);
glPopMatrix();

Downloads

You can download the project files for this tutorial right here: openglcircle3.zip.

Top · Tweet about this

Browse Articles

0 Opinions posted so far. Now go post your own. To the comment form!

Commenting is closed for this article.

Subscribe to this blog

About this blog

This is the personal weblog of Jan Vantomme.
I write about the everyday things that move me as a designer. I write shorter things on Twitter.

Add to Technorati Favorites

Some of the blogs I like

./ With Imagination
A JavaScript, CSS, XHTML web log focusing on usability and accessibility by Dustin Diaz
Adaptive Path
A blog on User Experience
The Man In Blue
A blog on web technology by Cameron Adams
Sarah Verroken
A blog on Illustration by Sarah Verroken
DevKick
Web Development for Designers