我們在很多網站會看到一些圖形的百分比顯示圖,像三個地區所占地多少或者是成績等一下我來給大家介紹一款用php生成的扇形比例百分比顯示程序代碼
不過使用它首先得有phpGD庫支持。
代碼如下 復制代碼
<?php
//填充圖表的參數
$ChartDiameter = 60; //圖表直徑
$ChartData = array(30,70);//用於生成圖表的數據,可通過數據庫來取得來確定也可以多個不過和顏色數組對應
//把角度轉換為弧度
function radians($degrees){return($degrees*(pi()/180.0));}
//取得在圓心為(0,0)圓上 x,y點的值
function circle_point($degrees,$diameter){$x=cos(radians($degrees))*($diameter/2);$y=sin(radians($degrees))*($diameter/2);return (array($x,$y));}
//確定圖形的大小
$ChartWidth = $ChartDiameter + 20;
$ChartHeight = $ChartDiameter + 20;
//確定統計的總數
$ChartTotal = “”;
for($index = 0;$index < count($ChartData);$index++){
$ChartTotal += $ChartData[$index];
}
$ChartCenterX = $ChartDiameter/2 + 10;
$ChartCenterY = $ChartDiameter/2 + 10;
//生成空白圖形
$image = imagecreate($ChartWidth, $ChartHeight);
//分配顏色
$colorBody = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$colorBorder = imagecolorallocate($image, 0×00, 0×00, 0×00);
$colorText = imagecolorallocate($image, 0×00, 0×00, 0×00);
$colorSlice[] = imagecolorallocate($image, 0xFF, 0×00, 0×00);//這裡是和你上面寫的數組對應的顏色
$colorSlice[] = imagecolorallocate($image, 0×00, 0xFF, 0×00);
//填充背境
imagefill($image, 0, 0, $colorBody);
//畫每一個扇形
$Degrees = 0;
for($index = 0; $index < count($ChartData); $index++){
$StartDegrees = round($Degrees);
$Degrees += (($ChartData[$index]/$ChartTotal)*360);
$EndDegrees = round($Degrees);
$CurrentColor = $colorSlice[$index%(count($colorSlice))];
//畫圖F
imagearc($image,$ChartCenterX,$ChartCenterY,$ChartDiameter,$ChartDiameter,$StartDegrees,$EndDegrees, $CurrentColor);
//畫直線
list($ArcX, $ArcY) = circle_point($StartDegrees, $ChartDiameter);
imageline($image,$ChartCenterX,$ChartCenterY,floor($ChartCenterX + $ArcX),
floor($ChartCenterY + $ArcY),$CurrentColor);
//畫直線
list($ArcX, $ArcY) = circle_point($EndDegrees, $ChartDiameter);
imageline($image,$ChartCenterX,$ChartCenterY,ceil($ChartCenterX + $ArcX),
ceil($ChartCenterY + $ArcY),$CurrentColor);
//填充扇形
$MidPoint = round((($EndDegrees – $StartDegrees)/2) + $StartDegrees);
list($ArcX, $ArcY) = circle_point($MidPoint, $ChartDiameter/2);
imagefilltoborder($image,floor($ChartCenterX + $ArcX),floor($ChartCenterY + $ArcY),
$CurrentColor,$CurrentColor);
}
//到此腳本 已經生了一幅圖像的,現在需要的是把它發到浏覽器上,重要的一點是要將標頭發給浏覽器,讓它知道是一個GIF文件。不然的話你只能看到一堆奇怪的亂碼
header(“Content-type: image/png”);
imagegif($image);
?>