Calculate a polygon's area in C#
Add the areas of the trapezoids defined by the polygon's edges dropped to the X-axis. When the program considers a bottom edge of a polygon, the calculation gives a negative area so the space between the polygon and the axis is subtracted, leaving the polygon's area. This method gives strange results for non-simple polygons (where edges cross).
private float SignedPolygonArea()The total calculated area is negative if the polygon is oriented clockwise. (For more on polygon orientation, see Determine whether a polygon's points are oriented clockwise in C#.) The PolygonArea function simply returns the absolute value of the result given by SignedPolygonArea.
{
// Add the first point to the end.
int num_points = Points.Length;
PointF[] pts = new PointF[num_points + 1];
Points.CopyTo(pts, 0);
pts[num_points] = Points[0];
// Get the areas.
float area = 0;
for (int i = 0; i < num_points; i++)
{
area +=
(pts[i + 1].X - pts[i].X) *
(pts[i + 1].Y + pts[i].Y) / 2;
}
// Return the result.
return area;
}
public float PolygonArea()
{
// Return the absolute value of the signed area.
// The signed area is negative if the polyogn is
// oriented clockwise.
return Math.Abs(SignedPolygonArea());
}



Comments