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

Ionel Lupu picture Ionel Lupu · Jan 25, 2012 · Viewed 30.5k times · Source

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

Answer

Kathir Softwareandfinance picture Kathir Softwareandfinance · Nov 22, 2013

Here is the code for drawing circle with pixels: It uses the formula xend = x + r cos(angle) and yend = y + r sin(angle).

#include <stdio.h>
#include <graphics.h>
#include <stdlib.h>
#include <conio.h>
#include <bios.h>
#include <math.h>

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

      for(i = 0; i < 360; i += 0.1)
      {
            angle = i;
            x1 = r * cos(angle * PI / 180);
            y1 = r * sin(angle * PI / 180);
            putpixel(x + x1, y + y1, color);
      }
}

Reference: http://www.softwareandfinance.com/Turbo_C/DrawCircle.html