2015-09-27 85 views
0

我有這個問題,並沒有找到一個正確的方法來檢查給定的X,Y點是否在任意2維多邊形內。如何檢查2維點是否在C#中的多邊形內?

幾個小時後,我設法找到一種方法,它也考慮到在多邊形邊上的點數,以此作爲匹配。

+1

使用[GraphicsPath.AddPolygon()](https://msdn.microsoft.com/en-us/library/16k3da3w(v = vs.110).aspx)和[GraphicsPath.IsVisible](https:// msdn.microsoft.com/en-us/library/d20k495d(v=vs.110).aspx)? –

+0

當你使用WinForms時,它確實有效。 –

+0

...你是或者不是**使用WinForms?你還沒有指定你的環境。 =) –

回答

0

通過使用自定義類Vector2雙X和雙Y屬性,你可以使用下面的代碼來檢查,如果給定的「位置」是「點」的多邊形內:

public bool CheckCollision(Vector2[] Points, Vector2 Position) 
    { 
     double MinX = Points.Min(a => a.X); 
     double MinY = Points.Min(a => a.Y); 
     double MaxX = Points.Max(a => a.X); 
     double MaxY = Points.Max(a => a.Y); 

     if(Position.X < MinX || Position.X > MaxX || Position.Y < MinY || Position.Y > MaxY) 
      return false; 

     int I = 0; 
     int J = Points.Count() - 1; 
     bool IsMatch = false; 

     for(; I < Points.Count(); J = I++) 
     { 
      //When the position is right on a point, count it as a match. 
      if(Points[ I ].X == Position.X && Points[ I ].Y == Position.Y) 
       return true; 
      if(Points[ J ].X == Position.X && Points[ J ].Y == Position.Y) 
       return true; 

      //When the position is on a horizontal or vertical line, count it as a match. 
      if(Points[ I ].X == Points[ J ].X && Position.X == Points[ I ].X && Position.Y >= Math.Min(Points[ I ].Y, Points[ J ].Y) && Position.Y <= Math.Max(Points[ I ].Y, Points[ J ].Y)) 
       return true; 
      if(Points[ I ].Y == Points[ J ].Y && Position.Y == Points[ I ].Y && Position.X >= Math.Min(Points[ I ].X, Points[ J ].X) && Position.X <= Math.Max(Points[ I ].X, Points[ J ].X)) 
       return true; 

      if(((Points[ I ].Y > Position.Y) != (Points[ J ].Y > Position.Y)) && (Position.X < (Points[ J ].X - Points[ I ].X) * (Position.Y - Points[ I ].Y)/(Points[ J ].Y - Points[ I ].Y) + Points[ I ].X)) 
      { 
       IsMatch = !IsMatch; 
      } 
     } 

     return IsMatch; 
    } 

我希望這幫助。 享受!

相關問題