Draw circle (using pixels applied in an image with for loop)
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);
}
}
Since you already have a BufferedImage
, why not create a graphics object for it and use that to draw the circle? That way you don't have to reinvent the wheel:
BufferedImage img = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics2D g = img.createGraphics();
g.setColor(Color.WHITE);
g.fillOval(x, y, width, height);
Update
Here is a SSCCE:
public class DrawCircleExample extends Canvas {
private static final int WIDTH = 32;
private static final int HEIGHT = 32;
public static void main(String[] args) {
JFrame f = new JFrame("Draw circle example");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new DrawCircleExample());
f.pack();
f.setVisible(true);
}
private final BufferedImage img;
public DrawCircleExample() {
img = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics2D g = img.createGraphics();
g.setColor(Color.WHITE);
g.fillOval(8, 8, 14, 14);
}
@Override
public void paint(Graphics g) {
g.drawImage(img, 0, 0, null);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(img.getWidth(),img.getHeight());
}
}
It should produce an image like this:
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