2
$\begingroup$

How to draw a circle using circle equation $x^2+y^2=r^2$?

If I merely have an area of some sort, where I want to draw the circle, say $200 \times 200$, then can I merely loop through this like

for ( i,j in 200 x 200):
   j=sqrt(r^2-i^2)

or so.

$\endgroup$
2
  • $\begingroup$ Your pseudocode has a variable $j$ in the for loop and a variable $j$ being assigned to? Also taking the square root will give you the positive square root only so either you need to consider also collecting the negative root, or use a different approach such as through trig functions $\endgroup$
    – Nadiels
    Mar 17, 2017 at 18:35
  • 1
    $\begingroup$ That’s a very simple and straightforward approach, but is inefficient and, if what you’re doing is using the computed coordinates to turn pixels on, produces undesirable artifacts. The circle can end up with gaps in some places and blobs of pixels in others. You’ll get much better results with something like Bresenham’s algorithm. $\endgroup$
    – amd
    Mar 18, 2017 at 0:50

3 Answers 3

2
$\begingroup$

So you are on the right track! Try something like the following:

for (x in [0,200]):
  posY = round(sqrt(radius^2 - x^2))
  negY = round(-sqrt(radius^2 - x^2))
  fillPixel([x,posY], color)
  fillPixel([x,negY], color)

Obviously this is pseudocode, but hopefully it's enough to give you the idea. If you need any other help just comment! :)

N.B: I'm assuming that the circle does actually fit into a 200x200 grid of pixels. You should probably check this before entering the loop!

$\endgroup$
1
  • $\begingroup$ What if the thing inside sqrt() becomes negative? When radius < x^2. $\endgroup$
    – mavavilj
    Mar 18, 2017 at 7:12
1
$\begingroup$

This and some others are answered in e.g.:

CS G140 Graduate Computer Graphics Prof. Harriet Fell Spring 2009 Lecture 4 – January 28, 2009 https://www.ccs.neu.edu/home/fell/CSG140/Lectures/CSG140SP2009-4.pdf

$\endgroup$
0
$\begingroup$

Credit to Thomas Russel.

Here's a variation on Thomas Russell's answer that avoids taking the square root of a negative number. By limiting the range of x-values you also limit the y-values to the bounds of the circle as defined by the radius, $x^2+y^2=radius^2$:

for x in [-radius, radius]:
    y = sqrt(radius^2 - x^2)
    fillPixel([x, y], color)
    fillPixel([x, -y], color)
$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .