2

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): http://i.imgur.com/a5QNMuX.png?1

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());
...
4

1 回答 1

1

您必须在执行过程中单独填写每一行,但请注意,您必须调整x半径的边界。这有点类似于进行 2D(离散)集成。基本思想是x^2 + y^2 = r^2在外部边界,并且两者y都是r固定的,所以......:

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是一种四舍五入到最接近整数的安全方法(而不是仅采用floorwith 强制转换),因为bound它始终是正数。

于 2014-02-04T16:36:28.957 回答