[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Calculate the area of a polygon in C#

Calculate polygon area

Trapezoid area

You can calculate the area of a polygon by adding the areas of the trapezoids defined by the polygon's edges dropped to the X-axis. If two adjacent points along the polygon's edges have coordinates (x1, y1) and (x2, y2) as shown in the picture on the right, then the area (shown in blue) of that side's trapezoid is given by:

area = (x2 - x1) * (y2 + y1) / 2

When the program adds up all of the trapezoid areas, the sides on the polygon's bottom give negative areas because x1 > x2. Those areas cancel out the parts of the other trapezoids that lie outside of the polygon as shown in the picture below.

Combining trapezoid areas

This method gives strange results for self-intersecting polygons, although it does work if the polygon intersects the X axis.

The following code shows how the example's Polygon class calculates a polygon's "signed" area. The result is either the area or the negative off the area if the polygon is oriented backwards. (In other words, if it turns out the program adds the bottom area and subtracts the top area in the picture above.)

// Return the polygon's area in "square units." // The value will be negative if the polygon is // oriented clockwise. private float 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; }

This code creates an array of PointF objects and copies the polygon's points into it. It then repeats the first point in the last array entry to make looping over the polygon's line segments easier.

The code then loops over the polygon's segments, calculates the area under each, adds them up, and returns the total.

The total calculated area is negative if the polygon is oriented clockwise. (I'll post more on polygon orientation soon.)

The following PolygonArea method simply returns the absolute value of the result given by the SignedPolygonArea method.

// Return the polygon's area in "square units." 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()); }

Download the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.