Hatefiend - 5 months ago 29

Java Question

I have a

`BufferedImage`

`radius`

`x`

`y`

I do not want to loop through it in a square fashion.

`pi * r^2`

`4 * r^2`

`4 / pi`

`x`

`y`

`radius`

`BufferedImage`

Examples:

`O`

`X`

Radius 1

`X O X`

O O O

X O X

Radius 2

`X X O X X`

X O O O X

O O O O O

X O O O X

X X O X X

I think the proper way to do this is with trigonometric functions but I can't quite get it in my head. I know one easy part is that all Pixels up, left, right, and down in

`radius`

`private LinkedList<Integer> getPixelColorsInCircle(final int x, final int y, final int radius)`

{

final BufferedImage img; // Obtained somewhere else in the program via function call.

final LinkedList<Integer> ll = new Linkedlist<>();

for (...)

for (...)

{

int x = ...;

int y = ...;

ll.add(img.getRGB(x, y)); // Add the pixel

}

}

Answer

Having the center of the circle `O(x,y)`

and the radius `r`

the following coordinates `(j,i)`

will cover the circle.

```
for (int i = y-r; i < y+r; i++) {
for (int j = x; (j-x)^2 + (i-y)^2 <= r^2; j--) {
//in the circle
}
for (int j = x+1; (j-x)*(j-x) + (i-y)*(i-y) <= r*r; j++) {
//in the circle
}
}
```

Description of the approach:

- Go from the top to the bottom perpendicularly through the line which goes through the circle center.
- Move horizontally till you reach the coordinate outside the circle, so you only hit two pixels which are outside of the circle in each row.
- Move till the lowest row.

As it's only the approximation of a circle, prepare for it might look like a square for small `r`

s

Ah, and in terms of Big-O, making 4 times less operations doesn't change complexity.

`Big-O =/= complexity`