How can I determine whether a 2D Point is within a Polygon?

前端 未结 30 2079
醉梦人生
醉梦人生 2020-11-21 05:06

I\'m trying to create a fast 2D point inside polygon algorithm, for use in hit-testing (e.g. Polygon.contains(p:Point)). Suggestions for effective tech

30条回答
  •  悲&欢浪女
    2020-11-21 05:48

    C# version of nirg's answer is here: I'll just share the code. It may save someone some time.

    public static bool IsPointInPolygon(IList polygon, Point testPoint) {
                bool result = false;
                int j = polygon.Count() - 1;
                for (int i = 0; i < polygon.Count(); i++) {
                    if (polygon[i].Y < testPoint.Y && polygon[j].Y >= testPoint.Y || polygon[j].Y < testPoint.Y && polygon[i].Y >= testPoint.Y) {
                        if (polygon[i].X + (testPoint.Y - polygon[i].Y) / (polygon[j].Y - polygon[i].Y) * (polygon[j].X - polygon[i].X) < testPoint.X) {
                            result = !result;
                        }
                    }
                    j = i;
                }
                return result;
            }
    

提交回复
热议问题