fast algorithm for drawing filled circles?

CAlgorithmGraphicsGeometry

C Problem Overview


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.

C Solutions


Solution 1 - C

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.

Solution 2 - C

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);

Solution 3 - C

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");

Solution 4 - C

You can use this:

void DrawFilledCircle(int x0, int y0, int radius)
{
	int x = radius;
	int y = 0;
	int xChange = 1 - (radius << 1);
	int yChange = 0;
	int radiusError = 0;

	while (x >= y)
	{
		for (int i = x0 - x; i <= x0 + x; i++)
		{
			SetPixel(i, y0 + y);
			SetPixel(i, y0 - y);
		}
		for (int i = x0 - y; i <= x0 + y; i++)
		{
			SetPixel(i, y0 + x);
			SetPixel(i, y0 - x);
		}

		y++;
		radiusError += yChange;
		yChange += 2;
		if (((radiusError << 1) + xChange) > 0)
		{
			x--;
			radiusError += xChange;
			xChange += 2;
		}
	}
}

Solution 5 - C

I like palm3D's answer. For being brute force, this is an amazingly fast solution. There are no square root or trigonometric functions to slow it down. Its one weakness is the nested loop.

Converting this to a single loop makes this function almost twice as fast.

int r2 = r * r;
int area = r2 << 2;
int rr = r << 1;

for (int i = 0; i < area; i++)
{
	int tx = (i % rr) - r;
	int ty = (i / rr) - r;
	
	if (tx * tx + ty * ty <= r2)
		SetPixel(x + tx, y + ty, c);
}

This single loop solution rivals the efficiency of a line drawing solution.

            int r2 = r * r;
			for (int cy = -r; cy <= r; cy++)
			{
				int cx = (int)(Math.Sqrt(r2 - cy * cy) + 0.5);
				int cyy = cy + y;

				lineDDA(x - cx, cyy, x + cx, cyy, c);
			}

Solution 6 - C

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;
}

Solution 7 - C

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.

Solution 8 - C

Here's how I'm doing it:
I'm using fixed point values with two bits precision (we have to manage half points and square values of half points)
As mentionned in a previous answer, I'm also using square values instead of square roots.
First, I'm detecting border limit of my circle in a 1/8th portion of the circle. I'm using symetric of these points to draw the 4 "borders" of the circle. Then I'm drawing the square inside the circle.

Unlike the midpoint circle algorith, this one will work with even diameters (and with real numbers diameters too, with some little changes).

Please forgive me if my explanations were not clear, I'm french ;)

void DrawFilledCircle(int circleDiameter, int circlePosX, int circlePosY)
{
	const int FULL = (1 << 2);
	const int HALF = (FULL >> 1);

	int size = (circleDiameter << 2);// fixed point value for size
	int ray = (size >> 1);
	int dY2;
	int ray2 = ray * ray;
	int posmin,posmax;
	int Y,X;
	int x = ((circleDiameter&1)==1) ? ray : ray - HALF;
	int y = HALF;
	circlePosX -= (circleDiameter>>1);
	circlePosY -= (circleDiameter>>1);

	for (;; y+=FULL)
	{
		dY2 = (ray - y) * (ray - y);

		for (;; x-=FULL)
		{
			if (dY2 + (ray - x) * (ray - x) <= ray2) continue;

			if (x < y)
			{
				Y = (y >> 2);
				posmin = Y;
				posmax = circleDiameter - Y;

				// Draw inside square and leave
				while (Y < posmax)
				{
					for (X = posmin; X < posmax; X++)
						setPixel(circlePosX+X, circlePosY+Y);
					Y++;
				}
				// Just for a better understanding, the while loop does the same thing as:
				// DrawSquare(circlePosX+Y, circlePosY+Y, circleDiameter - 2*Y);
				return;
			}

			// Draw the 4 borders
			X = (x >> 2) + 1;
			Y = y >> 2;
			posmax = circleDiameter - X;
			int mirrorY = circleDiameter - Y - 1;

			while (X < posmax)
			{
				setPixel(circlePosX+X, circlePosY+Y);
				setPixel(circlePosX+X, circlePosY+mirrorY);
				setPixel(circlePosX+Y, circlePosY+X);
				setPixel(circlePosX+mirrorY, circlePosY+X);
				X++;
			}
			// Just for a better understanding, the while loop does the same thing as:
			// int lineSize = circleDiameter - X*2;
			// Upper border:
			// DrawHorizontalLine(circlePosX+X, circlePosY+Y, lineSize);
			// Lower border:
			// DrawHorizontalLine(circlePosX+X, circlePosY+mirrorY, lineSize);
			// Left border:
			// DrawVerticalLine(circlePosX+Y, circlePosY+X, lineSize);
			// Right border:
			// DrawVerticalLine(circlePosX+mirrorY, circlePosY+X, lineSize);

			break;
		}
	}
}

void DrawSquare(int x, int y, int size)
{
	for( int i=0 ; i<size ; i++ )
		DrawHorizontalLine(x, y+i, size);
}

void DrawHorizontalLine(int x, int y, int width)
{
	for(int i=0 ; i<width ; i++ )
		SetPixel(x+i, y);
}

void DrawVerticalLine(int x, int y, int height)
{
	for(int i=0 ; i<height ; i++ )
		SetPixel(x, y+i);
}

To use non-integer diameter, you can increase precision of fixed point or use double values. It should even be possible to make a sort of anti-alias depending on the difference between dY2 + (ray - x) * (ray - x) and ray2 (dx² + dy² and r²)

Solution 9 - C

If you want a fast algorithm, consider drawing a polygon with N sides, the higher is N, the more precise will be the circle.

Solution 10 - C

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

Solution 11 - C

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);

      }

   }

}

Solution 12 - C

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;
	}
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhorseyguyView Question on Stackoverflow
Solution 1 - CAakashMView Answer on Stackoverflow
Solution 2 - Cpalm3DView Answer on Stackoverflow
Solution 3 - CDaniel EarwickerView Answer on Stackoverflow
Solution 4 - CLeszek SzaryView Answer on Stackoverflow
Solution 5 - CkmillenView Answer on Stackoverflow
Solution 6 - CAlexGeorgView Answer on Stackoverflow
Solution 7 - CArphimigonView Answer on Stackoverflow
Solution 8 - CGreg JosephView Answer on Stackoverflow
Solution 9 - CRamy Al ZuhouriView Answer on Stackoverflow
Solution 10 - CKPexEAView Answer on Stackoverflow
Solution 11 - CDisembleergonView Answer on Stackoverflow
Solution 12 - CZY4NView Answer on Stackoverflow