「PHP入門」円グラフを生成クラスとサンプルプログラム

1.ファイル名
piechart.cls.php
2.画像生成クラスのサンプルコード:
<?php
/*
* 円グラフ画像を生成
*/
class PieChart {
private $center; //円グラフの中点
private $width; //円グラフの直径
private $image; //円グラフオブジェクト

function __construct($width,$backcolor = array(array(“r"=>0xFF,"g"=>0xFF,"b"=>0xFF))) {
$this->width = $width;
$this->center = $width / 2;

//円グラフ画像を生成
$this->image = imagecreatetruecolor($this->width, $this->width);

//初期の図形に白を充填
$color = imagecolorallocate($this->image, $backcolor[0][“r"], $backcolor[0][“g"], $backcolor[0][“b"]);
imagefill($this->image, 0, 0, $color);
}

//図形データを設定
public function graphData($data, $colors){
$black = imagecolorallocate($this->image, 0x00, 0x00, 0x00);

$sum = array_sum($data);

$start = -90;

for($i=0; $i<count($data); $i++){
$color = imagecolorallocate($this->image, $colors[$i][“r"], $colors[$i][“g"], $colors[$i][“b"]);

$stop = @($data[$i] / $sum * 360) + $start;

imagefilledarc($this->image, $this->center, $this->center,
$this->width, $this->width, $start, $stop, $color, IMG_ARC_PIE);
imagefilledarc($this->image, $this->center, $this->center,
$this->width, $this->width, $start, $stop, $black, IMG_ARC_NOFILL | IMG_ARC_EDGED);

$start = $stop;
}
}

//図形を生成
public function flushImage(){
header(“Content-type:image/png");
imagepng($this->image);
}
}
?>

3.クラスファイルを呼び出す
<?php

include_once 'piechart.cls.php’;

$total = $_GET[“total"];
$count = $_GET[“count"];

$data = array($total-$count,$count);
$colors = array(
array('r’=>0xDD,’g’=>0xEE,’b’=>0xFF),
array('r’=>0xFF,’g’=>0xBB,’b’=>0xAA)
);

$chart = new PieChart(200,array(array(“r"=>0xF9,"g"=>0xF9,"b"=>0xF9)));
$chart->graphData($data, $colors);
$chart->flushImage();
?>

Development

Posted by arkgame