OpenGL ES for iPhone: Drawing a Circle - Part III

Posted by Jan Vantomme on 27 May 2009.
Tags: , , , ,

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 0720+= 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.70.71.0);
glDrawArrays(GL_TRIANGLE_FAN0361); 

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.70.71.0);
glDrawArrays(GL_TRIANGLE_FAN0361);
glPopMatrix(); 

Downloads

You can download the project files for this tutorial right here: openglcircle3.zip (XCode project with sample code to optimize a circle in OpenGL ES.).

Tweet this article