Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a filled circle?

Tags:

c++

c

I'm creating bitmap/bmp files according to the specifications with my C code and I would like to draw simple primitives on my bitmap. The following code shows how I draw a rectangle on my bitmap:

if(curline->type == 1) // draw a rectangle
{
    int xstart = curline->x;
    int ystart = curline->y;
    int width = curline->width + xstart;
    int height = curline->height + ystart;

    int x = 0;
    int y = 0;

    for(y = ystart; y < height; y++)
    {
      for(x = xstart; x < width; x++)
      {
        arr[x][y].blue = curline->blue;
        arr[x][y].green = curline->green;
        arr[x][y].red = curline->red;
      }
    }

    printf("rect drawn.\n");
}

...
save_bitmap();

Example output: enter image description here

So basically I'm setting the red, green and blue values for all pixels within the given x and y field.

Now I'd like to fill a circle by knowing its midpoint and radius. But how do I know which pixels are inside this circle and which pixels ain't? Any help would be appreciated, thanks for reading.

like image 293
beta Avatar asked Dec 12 '22 19:12

beta


2 Answers

A point lies within the bounds of a circle if the distance from the point to the center of the circle is less than the radius of the circle.

Consider a point (x1,y1) compared to a circle with center (x2,y2) and radius r:

int dx = x2 - x1; // horizontal offset
int dy = y2 - y1; // vertical offset
if ( (dx*dx + dy*dy) <= (r*r) )
{
    // set pixel color
}
like image 155
newb Avatar answered Dec 14 '22 10:12

newb


You can also try the midpoint algorithm, here on wikipedia.

like image 39
BlackBear Avatar answered Dec 14 '22 08:12

BlackBear