3

I am trying to test if a point lies within a circle and if the point is on the perimeter, it should be included in the results. However, Java's contains() implementation uses less than instead of less than or equal to. For example consider this snippet:

Ellipse2D.Double circle = new Ellipse2D.Double(0, 0, 100, 100);

System.out.println(circle.contains(50, 0));
System.out.println(circle.contains(50, 100));
System.out.println(circle.contains(0, 50));
System.out.println(circle.contains(100, 50));
System.out.println(circle.contains(50, 50));

This prints the following:

false
false
false
false
true

How can I achieve a value of true for all of those cases?

0

3 Answers 3

10

You have to decide what kind of tolerance your method will use. While your example uses points that are expressible in floating point, there are many points along the border of the ellipse which will not be, and so deciding whether a point is "on the border" isn't clear-cut. If you don't much care, then I would suggest making the ellipse slightly "bigger" than you actually want and using the built-in contains() method.

If you want to write your own method, it's as simple as taking the formula for an ellipse, plugging in the X and Y values of the point you wish to test, and observing the result:

bool isInsideOfOrOnBorderOfEllipse = ((x*x)/(a*a) + (y*y)/(b*b)) <= 1;

Note that this still runs into the problem of non-representable points, so some points that you think should be "on the border" won't be.

Update: Given that you're just using the built-in ellipse object (and thus specifying height/width rather than the general ellipse parameters) it would be worthwhile to have a look at the source for contains() here: http://hg.openjdk.java.net/jdk6/jdk6/jdk/file/ffa98eed5766/src/share/classes/java/awt/geom/Ellipse2D.java

Derive a new class, and then override contains(). In the overridden version, just copy the code, except use <= instead of < and you should be good.

0

You could use the method intersects. As javadoc says: Tests if the interior of this Ellipse2D intersects the interior of a specified rectangular area. Although it is not a circle (best representation of a tolerance around a point) works pretty well

This snippet should work for any x, y you want to check:

int size = 2;
...
ellipse.intersects(x - (size/2), y - (size/2), size, size);

It is just a rectangle around the point of interest. More size, nore tolerance

-1

Maybe getDistance() can help you here? Points on the prerimeter should return 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.