imagefilledpolygon() เป็นฟังก์ชันในตัวของ PHP ที่ใช้เพื่อวาดรูปหลายเหลี่ยมที่เติมสี
รูปแบบการใช้งาน (Syntax)
bool imagefilledpolygon($image, $points, $num_points, $color)
พารามิเตอร์
imagefilledpolygon() รับพารามิเตอร์ 4 ตัว ได้แก่ $image, $points, $num_points, และ $color
$image - สร้างภาพว่างในขนาดที่กำหนดโดยใช้ฟังก์ชัน imagecreatetruecolor()
$points - เก็บจุดมุม (vertices) ของรูปหลายเหลี่ยมตามลำดับ
$num_points - จำนวนจุดมุมทั้งหมดในรูปหลายเหลี่ยม จำนวนจุดต้องมีอย่างน้อย 3 จุดเพื่อสร้างรูปหลายเหลี่ยม
$color - รหัสสีเติมที่สร้างด้วยฟังก์ชัน imagecolorallocate()
ค่าที่คืนกลับ (Return Values)
คืนค่า True เมื่อสำเร็จ และ False เมื่อล้มเหลว
ตัวอย่างที่ 1
<?php
// ตั้งค่าอาร์เรย์จุดสำหรับรูปหลายเหลี่ยม
$values = array(
40, 50, // จุดที่ 1 (x, y)
20, 240, // จุดที่ 2 (x, y)
60, 60, // จุดที่ 3 (x, y)
240, 20, // จุดที่ 4 (x, y)
50, 40, // จุดที่ 5 (x, y)
10, 10 // จุดที่ 6 (x, y)
);
// สร้างภาพด้วยฟังก์ชัน imagecreatetruecolor
$img = imagecreatetruecolor(700, 350);
// จัดสรรสีน้ำเงินและสีเทา
$bg = imagecolorallocate($img, 122, 122, 122);
$blue = imagecolorallocate($img, 0, 0, 255);
// เติมพื้นหลัง
imagefilledrectangle($img, 0, 0, 350, 350, $bg);
// วาดรูปหลายเหลี่ยม
imagefilledpolygon($img, $values, 6, $blue);
// ส่งภาพ
header('Content-type: image/png');
imagepng($img);
imagedestroy($img);
?>
ผลลัพธ์

ตัวอย่างที่ 2
<?php
// ตั้งค่าจุดมุมของรูปหลายเหลี่ยม
$values = array(
150, 50, // จุดที่ 1 (x, y)
55, 119, // จุดที่ 2 (x, y)
91, 231, // จุดที่ 3 (x, y)
209, 231, // จุดที่ 4 (x, y)
245, 119 // จุดที่ 5 (x, y)
);
// สร้างขนาดภาพหรือภาพว่าง
$img = imagecreatetruecolor(700, 350);
// ตั้งสีพื้นหลังภาพเป็นสีเทา
$bg = imagecolorallocate($img, 122, 122, 122);
// ตั้งสีภาพเป็นสีแดง
$red = imagecolorallocate($img, 255, 0, 0);
// เติมพื้นหลัง
imagefilledrectangle($img, 0, 0, 350, 350, $bg);
// วาดภาพรูปหลายเหลี่ยม
imagefilledpolygon($img, $values, 5, $red);
// ผลลัพธ์ของภาพ
header('Content-type: image/png');
imagepng($img);
imagedestroy($img);
?>
ผลลัพธ์
