Center of gravity of a polygon

后端 未结 7 852
遥遥无期
遥遥无期 2020-12-02 16:13

I am trying to write a PHP function that will calculate the center of gravity of a polygon.

I\'ve looked at the other similar questions but I can\'t seem to find a s

相关标签:
7条回答
  • 2020-12-02 16:50

    In php:

    // Find the polygon's centroid.
    function getCenter($polygon)
    { 
        $NumPoints = count($polygon);
    
        if($polygon[$NumPoints-1] == $polygon[0]){
            $NumPoints--;
        }else{
            //Add the first point at the end of the array.
            $polygon[$NumPoints] = $polygon[0];
        }
    
        // Find the centroid.
        $X = 0;
        $Y = 0;
        For ($pt = 0 ;$pt<= $NumPoints-1;$pt++){
            $factor = $polygon[$pt][0] * $polygon[$pt + 1][1] - $polygon[$pt + 1][0] * $polygon[$pt][1];
            $X += ($polygon[$pt][0] + $polygon[$pt + 1][0]) * $factor;
            $Y += ($polygon[$pt][1] + $polygon[$pt + 1][1]) * $factor;
        }
    
        // Divide by 6 times the polygon's area.
        $polygon_area = ComputeArea($polygon);
        $X = $X / 6 / $polygon_area;
        $Y = $Y / 6 / $polygon_area;
    
        return array($X, $Y);
    }
    
    
    function ComputeArea($polygon)
    { 
        $NumPoints = count($polygon);
    
        if($polygon[$NumPoints-1] == $polygon[0]){
            $NumPoints--;
        }else{
            //Add the first point at the end of the array.
            $polygon[$NumPoints] = $polygon[0];
        }
    
        $area = 0;
    
        for ($i = 0; $i < $NumPoints; $i++) {
          $i1 = ($i + 1) % $NumPoints;
          $area += ($polygon[$i][1] + $polygon[$i1][1]) * ($polygon[$i1][0] - $polygon[$i][0]);
        }
    
        $area /= 2;
        return $area;
    }
    

    Read more at:

    PHP: How to determine the center of a Polygon

    0 讨论(0)
提交回复
热议问题