确定一个点是否在包括边缘在内的椭圆内 [英] Determining if a point lies within an ellipse, including the edge

查看:107
本文介绍了确定一个点是否在包括边缘在内的椭圆内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试一个点是否在圆内,以及该点是否在周长上,因此应将其包括在结果中。但是,Java的 contains()实现使用小于而不是小于或等于。例如,请考虑以下代码段:

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));

打印以下内容:

false
false
false
false
true

在所有这些情况下如何获得 true 的值?

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

推荐答案

您必须确定您的方法将使用哪种公差。虽然您的示例使用的是在浮点中可表示的点,但是椭圆的边界上有很多点不是,因此无法确定某个点是否在边界上 -切。如果您不太在意,那么我建议使椭圆比您实际想要的稍微大一些,并使用内置的 contains()方法。

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.

如果要编写自己的方法,则很简单,例如取一个椭圆的公式,插入要测试的点的X和Y值,然后观察结果:

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.

更新:假设您只是使用内置的椭圆对象(并且因此指定高度/宽度而不是常规的椭圆参数),值得在这里查看 contains()的源代码:http://hg.openjdk.java.net/jdk6/ jdk6 / jdk / file / ffa98eed5766 / src / share / classes / java / awt / geom / Ellipse2D.java

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.

这篇关于确定一个点是否在包括边缘在内的椭圆内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆