|Title||Find a polygon's centroid (center of mass) in Visual Basic .NET|
|Description||This example shows how to find a polygon's centroid (center of mass) in Visual Basic .NET.|
|Keywords||polygon, centroid, center of mass, graphics, VB.NET|
If you were to cut the polygon out of cardboard, the centroid would be the point where you could balance the polygon on a pin.
Note that the centroid does not necessarily lie on the polygon (imagine a donut shape with the centroid in the central hole) so you might need to glue the polygon to a piece of transparent plastic and place the pin on the plastic.
The formula for the centroid (X, Y) is given by:
X = SUM[(Xi + Xi+1) * (Xi * Yi+1 - Xi+1 * Yi)] / 6 / A
Y = SUM[(Yi + Yi+1) * (Xi * Yi+1 - Xi+1 * Yi)] / 6 / A
Here A is the area of the polygon and the sum is taken over all of the adjacent pairs of points. The following code shows the Visual Basic implementation.
' Find the polygon's centroid.
Public Function FindCentroid(ByVal points() As PointF) As _
' Add the first point at the end of the array.
ReDim Preserve points(points.Length)
points(points.Length - 1) = New PointF(points(0).X, _
' Find the centroid.
Dim X As Single = 0
Dim Y As Single = 0
Dim second_factor As Single
For i As Integer = 0 To points.Length - 2
second_factor = _
points(i).X * points(i + 1).Y - _
points(i + 1).X * points(i).Y
X += (points(i).X + points(i + 1).X) * second_factor
Y += (points(i).Y + points(i + 1).Y) * second_factor
' Divide by 6 times the polygon's area.
Dim polygon_area As Single = PolygonArea(points)
X /= (6 * polygon_area)
Y /= (6 * polygon_area)
' If the values are negative, the polygon is
' oriented counterclockwise. Reverse the signs.
If X < 0 Then
X = -X
Y = -Y
Return New PointF(X, Y)
For information on calculating the polygon's area, see the HowTo Calculate a polygon's area in Visual Basic .NET.
For more information on graphics programming in Visual Basic, see my book Visual Basic Graphics Programming.