How to traverse circle coordinates?

892 Views Asked by At

The problem I have is:

Fill a circle by drawing one-pixel-wide horizontal lines across its inside area.

My initial thought is to generate the circles' coordinates symmetrically to a vertical axis passing through its centre, using the parametric equations: \begin{align} x &= x_{\rm offset} + r \cdot \cos\theta \\ y &= y_{\rm offset} + r \cdot \sin\theta \end{align}

and letting the angle $\theta$ decrementing1 from $270^\circ$ to $180^\circ$, to generate the starting points of the horizontal lines and then incrementing1 for the $I$ and $IV$ quadrants: from $270^\circ$ to $360^\circ$ to generate the ending points of the lines.

As mathematics is clearly not my forte, I am asking the following:

Question:

  1. Should I proceed with the implementation of the above rationale or is there a more efficient2 method to achieve the task?

Note:

The coordinate system I use is left-handed: the $y$ coordinate increases downwards.


1. By the thickness of the lines

2. Using less calculations.

3

There are 3 best solutions below

0
On BEST ANSWER

For $r_y=-r\ldots r$, let $r_x=\sqrt{r^2-r_y^2}$ and draw the line at: $y=y_{\text{offset}}+r_y$
from $x=x_{\text{offset}}-r_x$ to $x=x_{\text{offset}}+r_x$.

0
On

Say that the circle has center $(a, b)$ and radius $r$. Its equation is $$ (x-a)^2 + (y-b)^2 = r^2. $$ For any particular $y$, we can solve for $x$ in terms of that $y$ to find the left and right endpoints of the horizontal segment: \begin{align} (x-a)^2 &= r^2 - (y-b)^2 \\ \lvert x-a \rvert &= \sqrt{r^2 - (y-b)^2} \\ x-a &= \pm \sqrt{r^2 - (y-b)^2} \\ x &= a \pm \sqrt{r^2 - (y-b)^2} \end{align}

Now, for each $y$ in the interval $[b-r, b+r]$, you have to draw the horizontal segment at height $y$ between the $x$-coordinates $$ a - \sqrt{r^2 - (y-b)^2} \quad\text{and}\quad a + \sqrt{r^2 - (y-b)^2}. $$

0
On

I see you already have accepted an answer... You are asking about a classical problem in computer graphics, which has been solved long time ago using only integer calculations.

Please see here for the description of the algorithm.