How to Calculate Centroid

后端 未结 4 1510
长情又很酷
长情又很酷 2021-02-06 03:15

I am working with geospatial shapes and looking at the centroid algorithm here,

http://en.wikipedia.org/wiki/Centroid#Centroid_of_polygon

I have implemented the

4条回答
  •  星月不相逢
    2021-02-06 03:50

    This answer is inspired by the answer by Jer2654 and this source: http://coding-experiments.blogspot.com/2009/09/xna-quest-for-centroid-of-polygon.html

      /// 
      /// Method to compute the centroid of a polygon. This does NOT work for a complex polygon.
      /// 
      /// points that define the polygon
      /// centroid point, or PointF.Empty if something wrong
      public static PointF GetCentroid(List poly)
      {
         float accumulatedArea = 0.0f;
         float centerX = 0.0f;
         float centerY = 0.0f;
    
         for (int i = 0, j = poly.Count - 1; i < poly.Count; j = i++)
         {
            float temp = poly[i].X * poly[j].Y - poly[j].X * poly[i].Y;
            accumulatedArea += temp;
            centerX += (poly[i].X + poly[j].X) * temp;
            centerY += (poly[i].Y + poly[j].Y) * temp;
         }
    
         if (Math.Abs(accumulatedArea) < 1E-7f)
            return PointF.Empty;  // Avoid division by zero
    
         accumulatedArea *= 3f;
         return new PointF(centerX / accumulatedArea, centerY / accumulatedArea);
      }
    

提交回复
热议问题