<?php
class PIE
{
private $im;
private $width;
private $height;
private $bg;
private $colors;
private $values;
private $angles;
public function __construct($width = 300, $height = 300)
{
$this->im = ImageCreateTrueColor($width, $height);
$this->width = $width;
$this->height = $height;
$this->bg = ImageColorAllocate($this->im, 255, 255, 255);
$this->colors = [];
$this->values = [];
$this->angles = [];
}
public function setBackgroundColor($red, $green, $blue)
{
$this->bg = ImageColorAllocate($this->im, $red, $green, $blue);
}
public function add($value, $color = null)
{
$this->values[] = floatval($value);
$this->colors[] = is_null($color) ? $this->generateRandomColor() : ImageColorAllocate($this->im, $color[0], $color[1], $color[2]);
}
public function render()
{
$this->draw();
ob_start();
ImagePNG($this->im);
$imageData = ob_get_clean();
retu 'data:image/png;base64,' . base64_encode($imageData);
}
public function saveAs($fileName)
{
$this->draw();
ImagePNG($this->im, $fileName . '.png');
}
public function __destruct()
{
ImageDestroy($this->im);
}
private function draw()
{
$this->fillBackground();
$this->calculateStartEndAngles();
foreach($this->values as $key => $value) {
$this->drawArc($value, $this->colors[$key], $this->angles[$key]['start'], $this->angles[$key]['end']);
}
}
private function fillBackground()
{
ImageFilledRectangle($this->im, 0, 0, $this->width, $this->height, $this->bg);
}
private function generateRandomColor()
{
retu ImageColorAllocate($this->im, rand(0, 255), rand(0, 255), rand(0, 255));
}
private function drawArc($value, $color, $start, $end)
{
$w = $this->width / 2;
$h = $this->height / 2;
ImageFilledArc($this->im, $w, $h, $w, $h, $start, $end, $color, IMG_ARC_PIE);
}
private function calculateStartEndAngles()
{
$this->angles = [];
$total = array_sum($this->values);
$start = 0;
foreach($this->values as $value) {
$angle = ($value / $total) * 360;
$this->angles[] = ['start' => $start, 'end' => $start + $angle];
$start += $angle;
}
}
}
<?php
require_once 'PIE.php';
$pie = new PIE(500, 500);
$pie->add(30, [255, 0, 0]);
$pie->add(40, [0, 255, 0]);
$pie->add(100, [0, 0, 255]);
$pie->add(200);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>PIE Chart with PHP</title>
</head>
<body>
<img src="<?= $pie->render() ?>" />
</body>
</html>
از مزایای این کلاس، امکان تعیین رنگ دلخواه برای هر بخش از نمودار و یا اجازه دادن به کلاس برای تولید رنگ تصادفی هست. همچنین محدودیتی در تعداد قطاعهای نمودار (تعداد مقادیر) وجود نداره. همچنین رنگ پس زمینه و ارتفاع و پهنای نمودار رو هم میتونید مشخص کنید. یکی دیگه از مزایای این کلاس اینه که میتونید خروجی رو هم توی فایل ذخیره کنید (متد saveAs) و هم مستقیماً نمایش بدین (متد render).
اگه درمورد نحوه کار و کدنویسی کلاس سؤالی بود در خدمتم.
- - , .
برچسب:
نویسنده: خنجی