ポイントがポリゴン内にあるかどうかを判断しようとしています。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;
}
ベストアンサー1
ここでコードをチェックしましたが、すべて問題があります。
最良の方法は次のとおりです。
/// <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.Length - 1;
for (int i = 0; i < polygon.Length; 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;
}