繁体   English   中英

如何检查圆是否位于凸多边形内部

[英]How to check if a circle lies inside of convex polygon

我想检查圆是否与凸多边形相交或位于凸多边形内。 我找到了一种很棒的方法来检测一个点是否在多边形内(从这里开始 ):

        public boolean insidePolygon(Vector2 [] vertices, Vector2 p)
        {
            int i, j;
            boolean c = false;
            int nvert = vertices.length;
            for (i = 0, j = nvert - 1; i < nvert; j = i++)
            {
                if (((vertices[i].Y > p.Y) != (vertices[j].Y > p.Y)) &&
                 (p.X < (vertices[j].X - vertices[i].X) * (p.Y - vertices[i].Y) / (vertices[j].Y - vertices[i].Y) + vertices[i].X))
                    c = !c;
            }
            return c;
        }

这适用于单个点,但有没有办法我们可以修改它来检查给定半径的圆是否在多边形内? 我想这是可能的,因为一个圆圈实际上是一个点,但更大,但我还是没有成功......

我可以想到两种方法:

第一种方式:
1)计算从圆的中心到每个边和每个顶点的距离,找到最小和最大距离,分别表示为Dmin和Dmax。
2)使用insidePolygon()函数检查圆的中心是否位于多边形内。
3)如果(R> Dmax)则圆圈包围多边形。
if(Dmin <R <Dmax)则圆与多边形相交。
如果(R <Dmin &&圆心在多边形内),则圆在多边形内。
if(R <Dmin &&圆心在多边形外),则圆在多边形外。

我不得不承认,这几乎与insidePolygon()使用的原始算法无关。

第二种方式:
通过距离=圆的半径向内偏移多边形。 如果生成的多边形仍然是有效多边形(即,不是自相交的)并保持相同的顶点遍历方向,请检查圆的中心是否在偏移多边形内。 如果是,则圆形在原始多边形内。

第二种方法更多地是使用原始算法,因为它通过圆的半径量向内偏移了polgon,从而实际上将圆减少到一个点。 但是,实施方面,第一种方式可能更容易。

有很多方法可以用数学方法完成它,但是我这样做的方法是使用Area类。 它可能不是最有效的表现方式,但速度足以满足我的需求,因为我不是数学专家,没有数学部分是一个加号:)

public bool polygonContains circle (Shape poly, Shape circle){
    Area p = new Area(poly);
    if (!p.contains(circle.center)) return false;
    Area a = new Area(poly);        
    Area c = new Area(circle);
    a.add(c);
    //get the pathiterator of a and one for area p and compare the points they return
    // if there is a point in a not in p, it means circle jets out of polygon so return false.
    //if you care about the circle touching the inside of the polygon then 
    Area m = new Area(poly);
    Area s = m.substract(c);
    //repeat the pathiterator comparison for p and s , if there is a point in s not found in a
    //it means the circle touched the edge of the polygon return the value you see fit.
    return true;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM