첨부 소스 코드는 나눔고딕코딩 폰트를 사용합니다.
728x90
반응형
728x170

▶ Point 클래스 : 다각형 내부 위치 여부 구하기 예제

List<Point> polygonPointList = new List<Point>
{
    new Point(100, 100),
    new Point(150, 130),
    new Point(120, 170),
    new Point(90 , 150),
    new Point(100, 100)
};

Point point = new Point(100, 150);

bool result = IsPointInPolygon(polygonPointList, point);

 

300x250

 

▶ Point 클래스 : 다각형 내부 위치 여부 구하기

#region 다각형 내부 위치 여부 구하기 - IsPointInPolygon(polygonPointList, point)

/// <summary>
/// 다각형 내부 위치 여부 구하기
/// </summary>
/// <param name="polygonPointList">다각형 포인트 리스트</param>
/// <param name="point">포인트</param>
/// <returns>다각형 내부 위치 여부</returns>
public bool IsPointInPolygon(IList<Point> polygonPointList, Point point)
{
    List<int> intersectList = new List<int>();

    Point currentPoint = polygonPointList.Last();

    foreach(Point polygonPoint in polygonPointList)
    {
        if(polygonPoint.X == point.X && polygonPoint.Y == point.Y)
        {
            return true;
        }

        if
        (
            polygonPoint.X == currentPoint.X &&
            point.X        == currentPoint.X &&
            point.X        >= Math.Min(currentPoint.Y, polygonPoint.Y) &&
            point.Y        <= Math.Max(currentPoint.Y, polygonPoint.Y)
        )
        {
            return true;
        }

        if
        (
            polygonPoint.Y == currentPoint.Y &&
            point.Y        == currentPoint.Y &&
            point.X        >= Math.Min(currentPoint.X, polygonPoint.X) &&
            point.X        <= Math.Max(currentPoint.X, polygonPoint.X)
        )
        {
            return true;
        }

        if((polygonPoint.Y < point.Y && currentPoint.Y >= point.Y) || (currentPoint.Y < point.Y && polygonPoint.Y >= point.Y))
        {
            int pointX = (int)(polygonPoint.X + 1.0 * (point.Y - polygonPoint.Y) / (currentPoint.Y - polygonPoint.Y) * (currentPoint.X - polygonPoint.X));

            intersectList.Add(pointX);
        }

        currentPoint = polygonPoint;
    }

    intersectList.Sort();

    return intersectList.IndexOf(point.X) % 2 == 0 || intersectList.Count(x => x < point.X) % 2 == 1;
}

#endregion
728x90
반응형
그리드형(광고전용)
Posted by icodebroker

댓글을 달아 주세요