Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw circle (using pixels applied in an image with for loop)

I want to draw a circle (with 1 or 2 for loops) using pixels position (starts from top left and ends at bottom right)

I successfully drew a rectangle with this method:

private void drawrect(int width,int height,int x,int y) {
    int top=y;
    int left=x;

    if(top<0){
        height+=top;
        top=0;
        }
    if(left<0){
        width+=left;
        left=0;
    }

    for (int j = 0; j <width; j++) {
        for (int i = 0; i <height; i++) {
                    pixels[((i+top)*w)+j+left] = 0xffffff;//white color
        }

    }

}

The pixels array contains the pixel index followed by it's color.

pixels[index]=color;

Before that I use this code for "image" and "pixels" array (if this helps you)

img = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
pixels = ((DataBufferInt) img.getRaster().getDataBuffer()).getData();

But how can I draw only the white pixels like in this image and ignore the other pixels?

Pixel Image

like image 780
Ionel Lupu Avatar asked Jan 25 '12 18:01

Ionel Lupu


People also ask

How do you make a circle in C++?

Syntax : circle(x, y, radius); where, (x, y) is center of the circle. 'radius' is the Radius of the circle.

How do you draw a circle in Java?

Draw a Circle Using the drawOval() Function in Java Now we call the drawOval() function and pass four arguments. The first two arguments are the x and y coordinates of the circle, while the last two arguments specify the width and the height of the circle to be drawn.


1 Answers

You can calculate the minimum angle between two pixels and improve the Kathir solution

...
void DrawCircle(int x, int y, int r, int color)
{
      static const double PI = 3.1415926535;
      double x1, y1;

      // calculates the minimun angle between two pixels in a diagonal.
      // you can multiply minAngle by a security factor like 0.9 just to be sure you wont have empty pixels in the circle
      double minAngle = acos(1 - 1/r);

      for(double angle = 0; angle <= 360; angle += minAngle)
      {
            x1 = r * cos(angle);
            y1 = r * sin(angle);
            putpixel(x + x1, y + y1, color);
      }
}
like image 111
leandro souza rosa Avatar answered Oct 11 '22 09:10

leandro souza rosa