Reputation: 1367
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:
Thanks for any help!
Upvotes: 1
Views: 313
Reputation: 56769
The problem is the math for indexing into pixels
array. The formula of x + y * width
is expecting discrete values for x
and y
. However as it stands y * width
is calculated as a double value, leading to the pixels being partially offset from the left side of the image even when x=0
.
You need to make sure x
and y
are normalized into int
values before they are used in the formula for indexing into pixels
:
pixels[(int)x + (int)y * width] = 0xFFFF00FF;
This gives the expected result.
Upvotes: 0
Reputation: 3761
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.
Upvotes: 2