PHP GD将坐标从极坐标转换为笛卡尔坐标



我想在图表的每个部分附近或上方显示百分比。

我必须将坐标从极坐标转换为笛卡尔坐标吗?

为了将极坐标(r, θ)转换为直角坐标(x, y),我使用了以下转换:

x = r * cos( θ )
y = r * sin( θ )

在这个图中

$x = $radius * cos( $Arc ); $y = $radius * sin( $Arc );

但结果不匹配(百分比值与图表的每个部分都不接近),我哪里错了?

我该怎么修?

<?php
$W = 500; $H = 500;
$Image = imagecreate($W,$H);
$colors = array();
imagecolorallocate($Image,150,150,150); // grey background
$colors[0] = imagecolorallocate($Image,255,0,0); // red
$colors[1] = imagecolorallocate($Image,100,255,10); // green
$colors[2] = imagecolorallocate($Image,0,0,255); // bleu
$colors[3] = imagecolorallocate($Image,255,255,0); // yellow
$Country = array('England', 'Northern Ireland', 'Scotland', 'Wales');
$Population = array(53012456,1810863,5295403,3063456);
$TotPopulation = array_sum($Population);
$radius = 300; $StarAngle = 0;
foreach($Population  as $index => $V )
{
    $Arc = (360 * $V) / $TotPopulation;
    $Percentage = (100 * $V) / $TotPopulation;
    imagefilledarc(
        $Image,
        $W / 2, $H / 2, //  center x,y
        $radius,
        $radius,
        $StarAngle,
        ($StarAngle + $Arc), // end arc
        $colors[$index],
        IMG_ARC_PIE
    );
    $x = $radius * cos($Arc);
    $y = $radius * sin($Arc);
    imagestring($Image, 15, 5, 30 + $index*15 , 'x= '.number_format($x, 2, '.', '').' y='.number_format($y, 2, '.', '').' Country='.$Country[$index].' %='. number_format($Percentage, 2, '.', '').' ' , $colors[$index]);
    $StarAngle += $Arc;
    imagestring($Image, 15, 5, 430 + $index*15 , 'Country='.$Country[$index].' Population= $V %='.number_format($Percentage, 2, '.', '').' ' , $colors[$index]);
}
imagestring($Image, 5, 35, 10 , 'The population of the United Kingdom year 2011' , $colors[3]);
imagepng($Image);

您可以尝试库geomath php

composer require rkondratuk/geo-math-php:^1

将极坐标转换为笛卡尔坐标:

<?php
use PhpGeoMathModelPolar3dPoint;
$polarPoint1 = new Polar3dPoint(
    40.758742779050706, -73.97855507715238, Polar3dPoint::EARTH_RADIUS_IN_METERS
);
$cartesianpoint1 = $polarPoint1->buildCartesian3DPoint();
// Result:
$cartesianpoint1->x;
$cartesianpoint1->y;
$cartesianpoint1->z;

将笛卡尔坐标转换为极坐标:

<?php
use PhpGeoMathModelCartesian3dPoint;
$x = 1001;
$y = 205;
$z = 512;
$cartesianPoint2 = new Cartesian3dPoint($x, $y, $z);
$polarPoint2 = $cartesianPoint2->buildPolar3dPoint();
// Result:
$polarPoint2->lat;
$polarPoint2->lng;
$polarPoint2->radius;

最新更新