Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

share|improve this question
add comment

2 Answers

up vote 6 down vote accepted

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).
share|improve this answer
add comment

Normally I have defined an ellipse with the center point, semi-major, semi-minor, and the angle of rotation.

What you have described is a ellipse that the center point needs to be determined, and is not rotated The most widely used algorithm in graphics for a circle is by Bresenham, Kennedy adapted it for an ellipse.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.