fast algorithm for drawing filled circles?

Viewed 89879

I am using Bresenham's circle algorithm for fast circle drawing. However, I also want to (at the request of the user) draw a filled circle.

Is there a fast and efficient way of doing this? Something along the same lines of Bresenham?

The language I am using is C.

13 Answers

Having read the Wikipedia page on Bresenham's (also 'Midpoint') circle algorithm, it would appear that the easiest thing to do would be to modify its actions, such that instead of

setPixel(x0 + x, y0 + y);
setPixel(x0 - x, y0 + y);

and similar, each time you instead do

lineFrom(x0 - x, y0 + y, x0 + x, y0 + y);

That is, for each pair of points (with the same y) that Bresenham would you have you plot, you instead connect with a line.

Just use brute force. This method iterates over a few too many pixels, but it only uses integer multiplications and additions. You completely avoid the complexity of Bresenham and the possible bottleneck of sqrt.

for(int y=-radius; y<=radius; y++)
    for(int x=-radius; x<=radius; x++)
        if(x*x+y*y <= radius*radius)
            setpixel(origin.x+x, origin.y+y);

Here's a C# rough guide (shouldn't be that hard to get the right idea for C) - this is the "raw" form without using Bresenham to eliminate repeated square-roots.

Bitmap bmp = new Bitmap(200, 200);

int r = 50; // radius
int ox = 100, oy = 100; // origin

for (int x = -r; x < r ; x++)
{
    int height = (int)Math.Sqrt(r * r - x * x);

    for (int y = -height; y < height; y++)
        bmp.SetPixel(x + ox, y + oy, Color.Red);
}

bmp.Save(@"c:\users\dearwicker\Desktop\circle.bmp");

Great ideas here! Since I'm at a project that requires many thousands of circles to be drawn, I have evaluated all suggestions here (and improved a few by precomputing the square of the radius):

http://quick-bench.com/mwTOodNOI81k1ddaTCGH_Cmn_Ag

enter image description here

The Rev variants just have x and y swapped because consecutive access along the y axis are faster with the way my grid/canvas structure works.

The clear winner is Daniel Earwicker's method ( DrawCircleBruteforcePrecalc ) that precomputes the Y value to avoid unnecessary radius checks. Somewhat surprisingly that negates the additional computation caused by the sqrt call.

Some comments suggest that kmillen's variant (DrawCircleSingleLoop) that works with a single loop should be very fast, but it's the slowest here. I assume that is because of all the divisions. But perhaps I have adapted it wrong to the global variables in that code. Would be great if someone takes a look.

EDIT: After looking for the first time since college years at some assembler code, I managed find that the final additions of the circle's origin are a culprit. Precomputing those, I improved the fastest method by a factor of another 3.7-3.9 according to the bench! http://quick-bench.com/7ZYitwJIUgF_OkDUgnyMJY4lGlA Amazing.

This being my code:

for (int x = -radius; x < radius ; x++)
{
    int hh = (int)std::sqrt(radius_sqr - x * x);
    int rx = center_x + x;
    int ph = center_y + hh;

    for (int y = center_y-hh; y < ph; y++)
        canvas[rx][y] = 1;
}

palm3D's brute-force algorithm I found to be a good starting point. This method uses the same premise, however it includes a couple of ways to skip checking most of the pixels.

First, here's the code:

int largestX = circle.radius;
for (int y = 0; y <= radius; ++y) {
    for (int x = largestX; x >= 0; --x) {
        if ((x * x) + (y * y) <= (circle.radius * circle.radius)) {
            drawLine(circle.center.x - x, circle.center.x + x, circle.center.y + y);
            drawLine(circle.center.x - x, circle.center.x + x, circle.center.y - y);
            largestX = x;
            break; // go to next y coordinate
        }
    }
}

Next, the explanation.

The first thing to note is that if you find the minimum x coordinate that is within the circle for a given horizontal line, you immediately know the maximum x coordinate. This is due to the symmetry of the circle. If the minimum x coordinate is 10 pixels ahead of the left of the bounding box of the circle, then the maximum x is 10 pixels behind the right of the bounding box of the circle.

The reason to iterate from high x values to low x values, is that the minimum x value will be found with less iterations. This is because the minimum x value is closer to the left of the bounding box than the centre x coordinate of the circle for most lines, due to the circle being curved outwards, as seen on this image The next thing to note is that since the circle is also symmetric vertically, each line you find gives you a free second line to draw, each time you find a line in the top half of the circle, you get one on the bottom half at the radius-y y coordinate. Therefore, when any line is found, two can be drawn and only the top half of the y values needs to be iterated over.

The last thing to note is that is that if you start from a y value that is at the centre of the circle and then move towards the top for y, then the minimum x value for each next line must be closer to the centre x coordinate of the circle than the last line. This is also due to the circle curving closer towards the centre x value as you go up the circle. Here is a visual on how that is the case.

In summary:

  1. If you find the minimum x coordinate of a line, you get the maximum x coordinate for free.
  2. Every line you find to draw on the top half of the circle gives you a line on the bottom half of the circle for free.
  3. Every minimum x coordinate has to be closer to the centre of the circle than the previous x coordinate for each line when iterating from the centre y coordinate to the top.

You can also store the value of (radius * radius), and also (y * y) instead of calculating them multiple times.

I would just generate a list of points and then use a polygon draw function for the rendering.

It may not be the algorithm yo are looking for and not the most performant one,
but I always do something like this:

void fillCircle(int x, int y, int radius){

   // fill a circle
   for(int rad = radius; rad >= 0; rad--){

      // stroke a circle
      for(double i = 0; i <= PI * 2; i+=0.01){

         int pX = x + rad * cos(i);
         int pY = y + rad * sin(i);

         drawPoint(pX, pY);

      }

   }

}

The following two methods avoid the repeated square root calculation by drawing multiple parts of the circle at once and should therefore be quite fast:

void circleFill(const size_t centerX, const size_t centerY, const size_t radius, color fill) {
    if (centerX < radius || centerY < radius || centerX + radius > width || centerY + radius > height) 
        return;

    const size_t signedRadius = radius * radius;
    for (size_t y = 0; y < radius; y++) {
        const size_t up = (centerY - y) * width;
        const size_t down = (centerY + y) * width;
        const size_t halfWidth = roundf(sqrtf(signedRadius - y * y));
        for (size_t x = 0; x < halfWidth; x++) {
            const size_t left = centerX - x;
            const size_t right = centerX + x;
            pixels[left + up] = fill;
            pixels[right + up] = fill;
            pixels[left + down] = fill;
            pixels[right + down] = fill;
        }
    }
}


void circleContour(const size_t centerX, const size_t centerY, const size_t radius, color stroke) {
    if (centerX < radius || centerY < radius || centerX + radius > width || centerY + radius > height) 
        return;
    
    const size_t signedRadius = radius * radius;
    const size_t maxSlopePoint = ceilf(radius * 0.707106781f); //ceilf(radius * cosf(TWO_PI/8));

    for (size_t i = 0; i < maxSlopePoint; i++) {
        const size_t depth = roundf(sqrtf(signedRadius - i * i));

        size_t left = centerX - depth;
        size_t right = centerX + depth;
        size_t up = (centerY - i) * width;
        size_t down = (centerY + i) * width;

        pixels[left + up] = stroke;
        pixels[right + up] = stroke;
        pixels[left + down] = stroke;
        pixels[right + down] = stroke;

        left = centerX - i;
        right = centerX + i;
        up = (centerY - depth) * width;
        down = (centerY + depth) * width;

        pixels[left + up] = stroke;
        pixels[right + up] = stroke;
        pixels[left + down] = stroke;
        pixels[right + down] = stroke;
    }
}

This was used in my new 3D printer Firmware, and it is proven the fastest way for filled circle of a diameter from 1 to 43 pixel. If larger is needed, the following memory block(or array) should be extended following a structure I wont waste my time explaining...

If you have questions, or need larger diameter than 43, contact me, I will help you drawing the fastest and perfect filled circles... or Bresenham's circle drawing algorithm can be used above those diameters, but having to fill the circle after, or incorporating the fill into Bresenham's circle drawing algorithm, will only result in slower fill circle than my code. I already benchmarked the different codes, my solution is 4 to 5 times faster. As a test I have been able to draw hundreds of filled circles of different size and colors on a BigTreeTech tft24 1.1 running on a 1-core 72 Mhz cortex-m4

https://www.youtube.com/watch?v=7_Wp5yn3ADI

// this must be declared anywhere, as static or global
// as long as the function can access it !

 uint8_t Rset[252]={
  0,1,1,2,2,1,2,3,3,1,3,3,4,4,2,3,4,5,5,5,2,4,5,5,
  6,6,6,2,4,5,6,6,7,7,7,2,4,5,6,7,7,8,8,8,2,5,6,7,
  8,8,8,9,9,9,3,5,6,7,8,9,9,10,10,10,10,3,5,7,8,9,
  9,10,10,11,11,11,11,3,5,7,8,9,10,10,11,11,12,12,
  12,12,3,6,7,9,10,10,11,12,12,12,13,13,13,13,3,6,
  8,9,10,11,12,12,13,13,13,14,14,14,14,3,6,8,9,10,
  11,12,13,13,14,14,14,15,15,15,15,3,6,8,10,11,12,
  13,13,14,14,15,15,15,16,16,16,16,4,7,8,10,11,12,
  13,14,14,15,16,16,16,17,17,17,17,17,4,7,9,10,12,
  13,14,14,15,16,16,17,17,17,18,18,18,18,18,4,7,9,
  11,12,13,14,15,16,16,17,17,18,18,18,19,19,19,19,
  19,7,9,11,12,13,15,15,16,17,18,18,19,19,20,20,20,
  20,20,20,20,20,7,9,11,12,14,15,16,17,17,18,19,19
  20,20,21,21,21,21,21,21,21,21};   
  
       // SOLUTION 1: (the fastest)
       
void FillCircle_v1(uint16_t x, uint16_t y, uint16_t r)
 { 
   // all needed variables are created and set to their value...
   uint16_t radius=(r<1) ? 1 : r ;
   if (radius>21 ) {radius=21; }
   uint16_t diam=(radius*2)+1;
   uint16_t ymir=0, cur_y=0;
   radius--; uint16_t target=(radius*radius+3*radius)/2; radius++;
 // this part draws directly into the ILI94xx TFT buffer mem. 
 // using pointers..2 versions where you can draw 
 // pixels and lines with coordinates will follow
   for (uint16_t yy=0; yy<diam; yy++) 
   { ymir= (yy<=radius) ? yy+target : target+diam-(yy+1);
   cur_y=y-radius+yy;
   uint16_t *pixel=buffer_start_addr+x-Rset[ymir]+cur_y*buffer_width;
   for (uint16_t xx= 0; xx<=(2*Rset[ymir]); xx++) 
   { *pixel++ = CANVAS::draw_color; }}} 



  // SOLUTION 2: adaptable to any system that can 
  // add a pixel at a time: (drawpixel or add_pixel,etc_)
  
void FillCircle_v2(uint16_t x, uint16_t y, uint16_t r)
 { 
   // all needed variables are created and set to their value...
   uint16_t radius=(r<1) ? 1 : r ;
   if (radius>21 ) {radius=21; }
   uint16_t diam=(radius*2)+1;
   uint16_t ymir=0, cur_y=0;
   radius--; uint16_t target=(radius*radius+3*radius)/2; radius++;
  for (uint16_t yy=0; yy<diam; yy++) 
  { ymir= (yy<=radius) ? yy+target : target+diam-(yy+1);
    cur_y=y-radius+yy;
    uint16_t Pixel_x=x-Rset[ymir];
    for (uint16_t xx= 0; xx<=(2*Rset[ymir]); xx++) 
     { //use your add_pixel or draw_pixel here
       // using those coordinates:
       // X position will be... (Pixel_x+xx)
       // Y position will be... (cur_y)
       // and add those 3 brackets at the end
   }}} 



  // SOLUTION 3: adaptable to any system that can draw fast 
  //                horizontal lines
 void FillCircle_v3(uint16_t x, uint16_t y, uint16_t r)
  { 
   // all needed variables are created and set to their value...
   uint16_t radius=(r<1) ? 1 : r ;
   if (radius>21 ) {radius=21; }
   uint16_t diam=(radius*2)+1;
   uint16_t ymir=0, cur_y=0;
   radius--; uint16_t target=(radius*radius+3*radius)/2; radius++;
   for (uint16_t yy=0; yy<diam; yy++) 
   { ymir= (yy<=radius) ? yy+target : target+diam-(yy+1);  
   cur_y=y-radius+yy;
   uint16_t start_x=x-Rset[ymir];
   uint16_t width_x=2*Rset[ymir];

   //  ... then use your best drawline function using those values:
   //  start_x:   position X of the start of the line
   //  cur_y:     position Y of the current line
   //  width_x:   length of the line
   //  if you need a 2nd coordinate then :end_x=start_x+width_x
   // and add those 2 brackets after !!!
 
    }}
Related