I am currently in the progress of using WritableRaster and it's setPixed method, and I need it to not set only one pixel, but a 'circle' with the radius of r. What I am thinking about is something like this:
for(int y = -r; y < r; y++)
{
for(int x = -r; x < r; x++)
{
raster.setPixel(x,y,color);
}}
The question is, would this work to make a circle, if so, how would I make it go through all the pixels inside?
Thanks in advance!
EDIT: Sorry I did not make this clear- I am making a rubber tool on a transparent canvas, thus, if I draw a circle with transparent color, it won't delete what was there before... This is why I am using setPixel.
EDIT EDIT: This is what the output of the code is (on g2d, using drawLine with same values so it only fills one pixel as in the method setPixel): https://i.sstatic.net/9ONWe.png
EDIT EDIT EDIT: If anyone wants to use this code for the same reason, I recommend using BufferedImage.setRGB() because it's much quicker. If you don't know what to do with the color (last parameter), use something like:
...
buffImg.setRGB(x,y,new Color(r,g,b,a).getRGB());
...
You would have to fill in each line individually as you are doing, but note that you have to adjust the bounds of x
for the radius. This is somewhat similar to doing a 2D (discrete) integration. The basic idea is that x^2 + y^2 = r^2
at the outer bounds, and both y
and r
are fixed, so...:
for(int y = -r; y < r; y++)
{
int bound = (int)(sqrt(r * r - y * y) + 0.5);
for(int x = -bound; x < bound; x++)
{
raster.setPixel(x,y,color);
}
}
... + 0.5
is a safe way to round to the nearest integer (instead of just taking the floor
with casting) since bound
will always be positive.