Imagepolygon tools
Posted: Sun Jan 23, 2005 3:30 pm
Imagepolygon() and imagefilledpolygon() both take an array of points. Sometimes when you're using these you want to move the polygon around and do stuff to it, but it can be tricky to work out the new coordinates.. not any more!
And a script that demonstrates the use of these handy functions:
Cool!
Code: Select all
function translatePolygon($points,$x=0,$y=0) {
for($i=0;$i<count($points);$i+=2) {
$pointsї$i] = $pointsї$i] + $x;
$pointsї$i+1] = $pointsї$i+1] + $y;
}
return $points;
}
function scalePolygon($points,$factor=1) {
for ($x=0;$x<count($points);$x++) {
$pointsї$x] = $pointsї$x]*$factor;
}
return $points;
}
function rotatePolygon($points,$degrees=0) {
$cos = cos(deg2rad($degrees));
$sin = sin(deg2rad($degrees));
for($i=0;$i<count($points);$i+=2) {
$minx = ($pointsї$i]<$minx or !isset($minx)) ? $pointsї$i] : $minx;
$miny = ($pointsї$i+1]<$miny or !isset($miny)) ? $pointsї$i+1] : $miny;
$maxx = ($pointsї$i]>$maxx or !isset($maxx)) ? $pointsї$i] : $maxx;
$maxy = ($pointsї$i+1]>$maxy or !isset($maxy)) ? $pointsї$i+1] : $maxy;
}
$mx = ($maxx-$minx)/2;
$my = ($maxy-$miny)/2;
for($i=0;$i<count($points);$i+=2) {
$x = $pointsї$i] - $mx - $minx;
$y = $pointsї$i+1] - $my - $miny;
$xdif = $cos*($x) - $sin*($y);
$ydif = $sin*($x) + $cos*($y);
$pointsї$i] = $minx + $xdif;
$pointsї$i+1] = $miny + $ydif;
}
return $points;
}Code: Select all
$points = array(
10, 0,
20, 0,
20, 10,
30, 10,
30, 20,
40, 20,
40, 30,
30, 30,
30, 40,
20, 40,
20, 30,
10, 30,
10, 20,
0, 20,
0, 10,
10, 10
);
$i = imagecreatetruecolor(400,400);
$white = imagecolorallocate($i,255,255,255);
imagefill($i,0,0,$white);
$red = imagecolorallocate($i,255,0,0);
$factor = 3;
$x = 100;
$y = 100;
$degrees = 45;
$points = scalePolygon($points,$factor);
$points = translatePolygon($points,$x,$y);
$points = rotatePolygon($points,$degrees);
imagefilledpolygon($i,$points,(count($points)/2),$red);
header("Content-type: image/jpeg");
imagejpeg($i);
function translatePolygon($points,$x=0,$y=0) {
for($i=0;$i<count($points);$i+=2) {
$pointsї$i] = $pointsї$i] + $x;
$pointsї$i+1] = $pointsї$i+1] + $y;
}
return $points;
}
function scalePolygon($points,$factor=1) {
for ($x=0;$x<count($points);$x++) {
$pointsї$x] = $pointsї$x]*$factor;
}
return $points;
}
function rotatePolygon($points,$degrees=0) {
$cos = cos(deg2rad($degrees));
$sin = sin(deg2rad($degrees));
for($i=0;$i<count($points);$i+=2) {
$minx = ($pointsї$i]<$minx or !isset($minx)) ? $pointsї$i] : $minx;
$miny = ($pointsї$i+1]<$miny or !isset($miny)) ? $pointsї$i+1] : $miny;
$maxx = ($pointsї$i]>$maxx or !isset($maxx)) ? $pointsї$i] : $maxx;
$maxy = ($pointsї$i+1]>$maxy or !isset($maxy)) ? $pointsї$i+1] : $maxy;
}
$mx = ($maxx-$minx)/2;
$my = ($maxy-$miny)/2;
for($i=0;$i<count($points);$i+=2) {
$x = $pointsї$i] - $mx - $minx;
$y = $pointsї$i+1] - $my - $miny;
$xdif = $cos*($x) - $sin*($y);
$ydif = $sin*($x) + $cos*($y);
$pointsї$i] = $minx + $xdif;
$pointsї$i+1] = $miny + $ydif;
}
return $points;
}