SteinSOFT.net
  Shapes I: Drawing A Circle

In the first part of the Shapes snippets, I will show you how to draw the easiest of the rather complex shapes. The famous, well-known circle. If you still remember what you learned in your trigonometry lessons, you should know that the the x-coordinate of a point on the unit circle - a circle whose radius is 1 - is cos § where § is the angle from the center of the circle to the point. The y-coordinate is sin §.

This makes drawing a circle absolutely easy. Here's the code:

#include <math.h> //we need cos(..) and sin(..)
  
const float DEG2RAD = 3.14159/180;
 
void drawCircle(float radius)
{
   glBegin(GL_LINE_LOOP);
 
   for (int i=0; i < 360; i++)
   {
      float degInRad = i*DEG2RAD;
      glVertex2f(cos(degInRad)*radius,sin(degInRad)*radius);
   }
 
   glEnd();
}

That's all! In this function we will iterate through 0-359° and draw for every angle the corresdonding point on the circle, using cos(..) and sin(..). Don't forget to convert degrees into radians as C/C++ trigonometry functions expect the angle to be in radians. You could also use a bigger or smaller range (e.g. 0-359 with steps of 0.1 ) if you want a higher/lower resolution of the circle.

We use GL_LINE_LOOP as we want to draw lines from one point to the other and we want the circle to be closed. If you would like the circle to be made of points, simply use GL_LINES. Little example how to use the function:

glColor3f(0.0f,1.0f,0.0f);
//draw circle with radius 1.5, hence a diameter(size) of 3
drawCircle(1.5f);

Questions? Suggestions? Mistakes? M@il me or visit the message board.

Copyright © by SteinSOFT