Calculating the Centroid of a Polygon in Java

Triangle CentroidI came across a defect at work the other day and part of the resolution to the bug entailed finding the centroid of a polygon. I went looking for a helper function that would calculate it in the javadocs and after a bit of searching I realized that it’s not a part of the Java 2D API (unless I’m missing something here). I’d be interested in knowing why a function to calculate the centroid isn’t a part of the Polygon class. Perhaps it has to do with the constraints that the polygon must not be self intersecting or maybe it’s because much of what you might want to do after you’ve found the centroid is better done using an AffineTransform. Here is a page with a nice description of the formula and example code and some util functions in a few different languages. More info on calculating the centroid of various shapes are here on wikipedia

This entry was posted in Algorithms, Java, Programming. Bookmark the permalink.

Comments are closed.