C++ – How to Draw an Ellipse from a Bounding Box

algorithmscgraphics

Does anyone know a good algorithm for drawing an ellipse from a bounding box?

draw_ellipse(int s1, int s2, int s3, int s4, color c); 

I don't need something optimized to incomprehendable , unreadable efficiency. Just something good enough to use for a simple drawing api. You can provide the algorithm in your answer in all programming languages or even pseudocode, but I would prefer it if you use C++ or a C++-like syntax.

Best Answer

A very basic and completely untested pseudo-code for drawing an ellipse using a parametric polar equation is below:

Function draw_ellipse(int X1, int Y1, int X2, int Y2)
     RX = (X2 - X1) / 2
     RY = (Y2 - Y1) / 2
     CX = (X2 + X1) / 2
     CY = (Y2 + Y1) / 2

     for Angle = 0 to 360
          X = CX + cos(Angle) * RX
          Y = CY + sin(Angle) * RY

          if (Angle > 0) DrawLine(LastX, LastY, X, Y)

          LastX = X
          LastY = Y
     Next Angle
End Function

Notes/Comments:

  • Assumes an unrotated ellipse.
  • Change to radians (0 to 2 pi) if your language cos/sin takes angles in radians (like C/C+ does).
  • You can use symmetry to reduce the loop size to 0 - 90 degrees.
  • Change the drawing precision as needed by changing the loop step amount (is 1 degree as shown).