Monday, March 12, 2012

C# code to determine if the polygon vertices are in the clockwise direction

In some GIS polygon data formats such as the ESRI shape file format, the holes of a polygon are stored in the counter-clockwise direction while the outer polygon is stored in the clockwise direction. If you are writing a program to read a polygon geometry containing holes, it may be necessary to determine the holes by checking whether the vertices are in the counter-clockwise or clockwise direction.

The C# code snippet below is useful to determine whether the vertices of a polygon are in the clockwise direction or counter clockwise direction. Simply pass in the polygon vertices into the function as an array of PointF structures where the first and last member of the array are the same point. The function will return true if the vertices are in the clockwise direction and false if they are in the counter-clockwise direction.


private bool IsClockwisePolygon(PointF[] polygon)
{
bool isClockwise = false;
double sum = 0;
for ( int i = 0; i < polygon.Length-1; i++)
{
sum += (polygon[i + 1].X - polygon[i].X) * (polygon[i + 1].Y + polygon[i].Y);
}
isClockwise = (sum > 0) ? true : false;
return isClockwise;
}

5 comments:

  1. Thank you, it was helpful. But I think this code gives wrong results in some cases. There is no sum += for the last and the first point in the polygon. So after the for cycle you should add:
    sum += (polygon[1].X - polygon[polygon.Length-1].X) * (polygon[1].Y + polygon[polygon.Length-1].Y);

    ReplyDelete
  2. Thanks for the comment. I should have made clear that it was for handling formats like the Shapefile polygon format, that has the same vertex for the first and last array members.

    ReplyDelete
  3. This can't be right... for a square, the result for this would be zero, because either the x- or y-component would be zero...?

    ReplyDelete
  4. Hi Jonathan, true that for a square the vertical segments' x-components would be zero but the horizontal components' x and y components are non-zero.

    ReplyDelete