Examlpes

Problem: Test if a point lies in a polygon

The method provides a test if a point lies inside an arbitrary shaped convex or concave poylgon. The polygon is defined by a polyline object. The polyline must be closed and must not be self-intersecting or the test may produce incorrect results.

 

Solution using G#

  1.  public static void PointInPolygonTest()
  2.   {
  3.       // Create a closed sample polygon
  4.       Polyline pl = new Polyline();
  5.       pl.Add(new Edge(new Point(2.0000, 0.0000, 0), new Point(0.9239, 0.3827, 0)));
  6.       pl.Add(new Edge(new Point(0.9239, 0.3827, 0), new Point(1.4142, 1.4142, 0)));
  7.       pl.Add(new Edge(new Point(1.4142, 1.4142, 0), new Point(0.3827, 0.9239, 0)));
  8.       pl.Add(new Edge(new Point(0.3827, 0.9239, 0), new Point(0.0000, 2.0000, 0)));
  9.       pl.Add(new Edge(new Point(0.0000, 2.0000, 0), new Point(-0.3827, 0.9239, 0)));
  10.       pl.Add(new Edge(new Point(-0.3827, 0.9239, 0), new Point(-1.4142, 1.4142, 0)));
  11.       pl.Add(new Edge(new Point(-1.4142, 1.4142, 0), new Point(-0.9239, 0.3827, 0)));
  12.       pl.Add(new Edge(new Point(-0.9239, 0.3827, 0), new Point(-2.0000, 0.0000, 0)));
  13.       pl.Add(new Edge(new Point(-2.0000, 0.0000, 0), new Point(2.0000, 0.0000, 0)));
  14.  
  15.       // Test a point
  16.       Point p1 = new Point(0.5, 1.5, 0);
  17.       Point p2 = new Point(0.0, 1.5, 0);
  18.       Console.WriteLine(pl.Contains(p1)); //false
  19.       Console.WriteLine(pl.Contains(p2)); //true
  20.      
  21.       //Visualize
  22.       Scene sc = new Scene();
  23.       sc.PointDisplayMode = 3;
  24.       Scene.Layer lay1 = new Scene.Layer("Polygon", 1);
  25.       Scene.Layer lay2 = new Scene.Layer("Points",7);
  26.       for (int i = 0; i < pl.Count; i++)
  27.       {
  28.           sc.Add(pl[i], lay1);
  29.       }
  30.       sc.Add(p1, lay2);
  31.       sc.Add(p2, lay2);
  32.       sc.WriteDxf(@"e:\polygon.dxf");
  33.       Console.ReadLine();
  34.    }

Output

A closed, non-selfintersecting polygon and two points to be tested.

<< back