Search code examples
algorithmdrawingprimitive

Drawing a circle segment


I am wondering if anyone here can help me with some pseudocode or at least point me in the right direction on how to draw a circle segment without anti-aliasing.


Solution

  • The formula for points on a circle are:

    x = xcenter + radius * sin(theta)
    y = ycenter + radius * cos(theta)
    

    where xcenter and ycenter are the center of the circle, radius is the radius and theta is the angle.

    You simply have to iterate theta from your starting angle to your ending angle in small enough steps, and extract the x and y values for plotting, and keep in mind that most trigonometric functions take their arguments as radians (0 through 2*PI) rather than degrees (0 through 360) - adjust your start and end angles and your theta step to take this into account.

    Pseudo-code would be something like the following:

    def plotCirle (xc, yc, rad, start, end):
        theta = start
        while theta <= end:
            x = xc + rad * sin (theta)
            y = yc + rad * cos (theta)
            plot (x, y)
            theta = theta + 0.01
    

    although you'd probably want to normalise the angles to be between 0 and 2*PI, and then swap the start and end angles if the former is greater than the latter.

    If you want more efficient code, you can look into the midpoint circle algorithm. The math is heavier and it's slightly complicated by the requirement that you only want a segment (meaning you'll need to know the angle, something not usually necessary for this algorithm with a full circle) but that might be a good starting point if the simplistic algorithm above is not fast enough.