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;
}
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:
ReplyDeletesum += (polygon[1].X - polygon[polygon.Length-1].X) * (polygon[1].Y + polygon[polygon.Length-1].Y);
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.
ReplyDeleteThank you, it was very helpful
ReplyDeleteThis can't be right... for a square, the result for this would be zero, because either the x- or y-component would be zero...?
ReplyDeleteHi 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