Lucas Romier Lucas Romier - 6 days ago 5
Java Question

Drawing circle the manual way in java returning strange result

I am trying to draw a circle with its origin in the middle of the screen:

width = canvas.getWidth();
height = canvas.getHeight();

BufferStrategy bufferStrategy = canvas.getBufferStrategy();
if(bufferStrategy == null){//If bufferStrategy is not initialized yet
canvas.createBufferStrategy(3);
bufferStrategy = canvas.getBufferStrategy();
}
Graphics graphics = bufferStrategy.getDrawGraphics();

public int[] pixels = new int[width * height];

int radius = height / 6;
for(int theta = 0; theta < 360; theta++){
double rads = Math.toRadians(theta);

double x = (width / 2) + (Math.cos(rads) * radius);
double y = (height / 2) + (Math.sin(rads) * radius);
pixels[(int)(x + y * width)] = 0xFFFF00FF;
}

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
image.setRGB(0, 0, width, height, pixels, 0, width);

graphics.drawImage(image, 0, 0, width, height, null);


But I am getting a weird result:

Result

Thanks for any help!

Answer

Cast your x and y values to ints before doing the math to figure out which of the pixels to change the color of.

int x = (int) ((width / 2) + (Math.cos(rads) * radius));
int y = (int) ((height / 2) + (Math.sin(rads) * radius));
pixels[(x + y * width)] = 0xFFFF00FF;

Doing it inline resulted in some rounding errors.

Comments