C# 多边形中的点

标签 c# .net algorithm

我正在尝试确定一个点是否在多边形内。 Polygon 由一组 Point 对象定义。我可以很容易地确定该点是否在多边形的有界框内,但我不确定如何判断它是否在实际多边形内。如果可能,我只想使用 C# 和 WinForms。我宁愿不调用 OpenGL 或其他东西来完成这个简单的任务。

这是我目前的代码:

private void CalculateOuterBounds()
{
    //m_aptVertices is a Point[] which holds the vertices of the polygon.
    // and X/Y min/max are just ints
    Xmin = Xmax = m_aptVertices[0].X;
    Ymin = Ymax = m_aptVertices[0].Y;

    foreach(Point pt in m_aptVertices)
    {
        if(Xmin > pt.X)
            Xmin = pt.X;

        if(Xmax < pt.X)
            Xmax = pt.X;

        if(Ymin > pt.Y)
            Ymin = pt.Y;

        if(Ymax < pt.Y)
            Ymax = pt.Y;
    }
}

public bool Contains(Point pt)
{
    bool bContains = true; //obviously wrong at the moment :)

    if(pt.X < Xmin || pt.X > Xmax || pt.Y < Ymin || pt.Y > Ymax)
        bContains = false;
    else
    {
        //figure out if the point is in the polygon
    }

    return bContains;
}

最佳答案

我检查过这里的代码,都存在问题。

最好的方法是:

    /// <summary>
    /// Determines if the given point is inside the polygon
    /// </summary>
    /// <param name="polygon">the vertices of polygon</param>
    /// <param name="testPoint">the given point</param>
    /// <returns>true if the point is inside the polygon; otherwise, false</returns>
    public static bool IsPointInPolygon4(PointF[] polygon, PointF 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;
    }

关于C# 多边形中的点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4243042/

相关文章:

c# - 如何使用 Web 服务在没有竞争条件的情况下写入数据库?

c# - 将 EntityFramework 实体绑定(bind)到 TreeView

c# - 在.NET Core应用程序中使用WinRT组件

.net - 使用 .Net 连接器配置 MySql 集群故障转移

.net - 自动更新 .NET 应用程序

c# - 企业服务总线(.NET 风格)——一次消费一批消息

ios - Swift:将 [String] 拆分为具有给定子数组大小的 [[String]] 的正确方法是什么?

从数据库中选择最受欢迎地点的算法

c# - svcutil.exe 或测试 wcf 服务 JSON 输出?

c++ - next_permutation() 的并行代码