Skip to content

Instantly share code, notes, and snippets.

@rcdilorenzo
Created February 1, 2014 18:40
Show Gist options
  • Save rcdilorenzo/8756611 to your computer and use it in GitHub Desktop.
Save rcdilorenzo/8756611 to your computer and use it in GitHub Desktop.
Simple Obj-C function to calculate centroid of points
CGPoint centroidOfPoints(const CGPoint* points, int pointCount) {
CGPoint centroid = CGPointMake(0, 0);
double x0, y0, x1, y1, partialArea;
double signedArea = 0.0;
for (int index = 0; index < pointCount; index++) {
int nextIndex = (index == pointCount-1) ? 0 : index+1;
x0 = points[index].x;
y0 = points[index].y;
x1 = points[nextIndex].x;
y1 = points[nextIndex].y;
partialArea = (x0 * y1) - (x1 * y0);
signedArea += partialArea;
centroid.x += (x0 + x1) * partialArea;
centroid.y += (y0 + y1) * partialArea;
}
signedArea /= 2;
centroid.x /= (6.0 * signedArea);
centroid.y /= (6.0 * signedArea);
NSLog(@"Signed Area: %E", signedArea);
return centroid;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment