Currently I am using Bresenham's circle drawing algorithm, which draws circles fine, however I would like a relatively fast and efficient way to draw a circle with a specified thickness (since Bresenham's method only draws a single pixel thickness). I realise that I could simply draw multiple circles with different radii, but I believe this would be very inefficient (and efficiency is important because this will be running on an Arduino where every microsecond is precious). I am currently using the following code:
void circle(byte xc, byte yc, int radius, Colour colour) {
int x = -radius, y = 0, err = 2 - 2 * radius;
while(x < 0) {
setPixel(xc - x, yc + y, colour);
setPixel(xc - y, yc - x, colour);
setPixel(xc + x, yc - y, colour);
setPixel(xc + y, yc + x, colour);
radius = err;
if(radius <= y) {
err += ++y * 2 + 1;
}
if(radius > x || err > y) {
err += ++x * 2 + 1;
}
}
}
How could I modify this to allow for specification of the circle's thickness? PS I don't want to use any external libraries, please!
If you scan along octants as explained for the Midpoint circle algorithm, your major coordinate
y
will always increase by one. You can then draw two circles at once, because their major coordinates are in sync.Instead of placing pixels, you draw horizontal (and vertical) lines between the points of the inner and outer circle, which have the same
y
(orx
) coordinate. You do so until the outer circle reaches the diagonal.You keep the state with
x
anderr
for two circles, the inner circlei
and the outer circleo
. After the inner circle has reached the diagonal, the inner point lies on that diagonal. This means you are drawing eight adjoining octant sectors.This idea is very similar to what @oakad proposed in the comments, but without the need for keeping a list. The Midpoint circle algorithm might be slower than the Bresenham algorithm, so there's probably room for improvement, but the low memory footprint is an advantage.
The code below will draw a hollow circle with the given inner and outer radii. The line width is
ro - ri + 1
, so that even equal radii will print a circle that is one pixel wide. It won't print anything if the inner radius is smaller than the outer radius.The solution below can be slow, however, it is very simple.
First, draw the inner and outern circles using Bresenham's algorithm. Then, check condition:
If it is satisfied, setPixel(i,j).