Reputation: 6107
I need to examine each pixel inside an oval with Java. For drawing, I am currently using:
drawOval(x,y,r*2,R*2).
However, since I need to get each pixel inside the Oval, I would like to create a loop that iterates inside it (assuming I have x,y,r and R). Is there any built in functionality for this purpose?
Thanks,
Joel
Upvotes: 1
Views: 1049
Reputation: 205785
Java's Ellipse2D
implements the Shape
interface, so you can use one of the latter's contains()
methods as required. It's also possible to render the Shape
into a BufferedImage
and traverse its WritableRaster
.
Upvotes: 2
Reputation: 47183
I don't think there's any built in functionality for this.
Let's go through this step by step.
Assuming that your ellipse's center is at (0,0)
, one radius is a
, other is b
, the canonical equation is
x^2/a^2+y^2/b^2=1
Multiplying both sides with a^2
and b^2
, you get
x^2*b^2+y^2*a^2=a^2*b^2
Now, you must do a double for loop. a
and b
must be positive. Pseudocode:
for x = -a; x <= a; ++x:
for y = -b; y <= b; ++y:
if(x^2*b^2+y^2*a^2 <= a^2*b^2)
// you're in your ellipse, do as you please
Of course, this will work only if center is at (0,0)
, so if you want this algorithm to work, shift your points appropriately using translation. If you leave the center somewhere else, this algorithm will get messier.
Note: didn't test this. If somebody sees a mistake, please point it out.
Upvotes: 1
Reputation: 15792
simple canonical implicit equation for Oval is (with center 0; 0)
So yo can iterate throw all possible coordinates and check it using this equation.
Upvotes: 1