

Title  Find a Region's centroid in Visual Basic .NET 
Description  This example shows how to find a Region's centroid in Visual Basic .NET. 
Keywords  geometry, graphics, algorithms, region, centroid, circles, overlap, circles overlap, Visual Basic .NET, VB.NET 
Categories  Algorithms, VB.NET 


The example Find the area where two or more circles overlap in Visual Basic .NET
shows how to find a Region representing the area where two or more circles overlap. This example shows how to find the centroid of that Region to get a point that is in the "center" of the Region.
The Region object's GetRegionData method returns information about the Region's shape. Unfortunately this data comes as an array of bytes and it's not obvious what to do with it.
The Region object's GetRegionScans method, however, returns an array of rectangles representing the region, and rectangles are much easier to understand.
This example uses the RegionCentroid method shown in the following code to find the centroid of a Region by using its scan rectangles.


' Return the centroid of the region.
Private Function RegionCentroid(ByVal the_region As Region, _
ByVal transform As Matrix) As PointF
Dim cx As Single = 0
Dim cy As Single = 0
Dim total_weight As Single = 0
For Each rect As RectangleF In _
the_region.GetRegionScans(transform)
Dim rect_weight As Single = rect.Width * rect.Height
cx += rect_weight * (rect.Left + rect.Width / 2.0F)
cy += rect_weight * (rect.Top + rect.Height / 2.0F)
total_weight += rect_weight
Next rect
Return New PointF(cx / total_weight, cy / total_weight)
End Function


The code initializes moment values cx and cy, and the region's total weight. It then loops through the rectangles, adding the moments of each to cx and cy, and adding the rectangle's weight to the total. When it finishes, the code divides the moments by the total weight to get the centroid's coordinates.





