pMpC
pMpC

Reputation: 257

Calculate the middle point of a shape

I want to do some transformation such as rotate and scale which need this method.

So, I'm having problems in the methods that i mentioned above that include this one but I can't find any errors (probably there are) in the respective ones. Is this method correct to determine the center point of a shape?

public Point getCentroid(){
    int sumx = 0;
    int sumy = 0;
    for(int i = 0; i<points.size();i++){
        sumx+=points.get(i).getX();
        sumy+=points.get(i).getY();
    }
     Point centroid = new Point(sumx/points.size(), sumy/points.size());
     return centroid;
}

Thanks in advance guys

//////////////////////////////////////////EDIT//////////////////////////////////////////////////

Something like this should work for sure then? (I'm asking because it's still not working, just want to know if it still because of calculating the center).

public Point getCentroid() {
    Vector<Integer> x = new Vector<Integer>();
    Vector<Integer> y = new Vector<Integer>();
    for(int i=0; i<points.size();i++){
        x.add((int) points.get(i).getX());
        y.add((int) points.get(i).getY());
    }
    Point p = new Point((Collections.max(x)-Collections.min(x))/2, (Collections.max(y)-Collections.min(y))/2);
    return p;
}

Upvotes: 2

Views: 2325

Answers (1)

Solomon Slow
Solomon Slow

Reputation: 27190

Your method correctly calculates the centroid of a collection of points, but I think that the answer to your question depends on how those point define the shape. For example, if the points represent an arbitrary closed polyline---the outline of the shape, then I think it's pretty easy to find an example where the centroid of the points does not coincide with the centroid of the enclosed area. Just imagine a square area with a bunch of redundant points near one corner....

Your method will calculate a point that lies somewhere within the convex-hull of the given set of points. Maybe that is good enough for what you want to do.

I don't know how to calculate the exact centroid of an arbitrary polygon, but you could compute an approximation by brute force: Rasterize the shape, and then compute the centroid of the pixels that fall within it.

------------- EDIT -------------

Your second example calculates the center of the bounding rectangle. Once again, this will not be the true centroid, but it may be satisfactory.

Why are you doing this? If it's for a physics-based simulation, then maybe you really need the true centroid, but if it's for a GUI, then the center of the bounding rectangle probably will provide a satisfactory user experience for most shapes.

Upvotes: 1

Related Questions