在 PHP 中,imageopenpolygon() 是一个非常有趣的函数,它允许你通过一组坐标点绘制开口(不封闭)的多边形。这在需要绘制复杂图形,例如星形或雪花图案时特别有用。
本文将通过实例讲解如何使用 imageopenpolygon(),并展示如何绘制一个简单的五角星和一个基础雪花结构。
bool imageopenpolygon(
GdImage $image,
array $points,
int $num_points,
int $color
)
$image:要绘制的图像资源。
$points:包含所有顶点坐标的数组,形式为 [x1, y1, x2, y2, ...]。
$num_points:顶点数量。
$color:线条的颜色。
注意:imageopenpolygon() 会按顺序连接这些点,但不会自动闭合图形。
首先,我们创建一个画布并绘制一个简单的五角星:
<?php
// 创建画布
$image = imagecreatetruecolor(300, 300);
// 分配颜色
$backgroundColor = imagecolorallocate($image, 255, 255, 255); // 白色背景
$starColor = imagecolorallocate($image, 255, 0, 0); // 红色星形
// 填充背景
imagefill($image, 0, 0, $backgroundColor);
// 定义五角星顶点
$points = [
150, 20, // 顶部
179, 110,
270, 110,
197, 165,
220, 250,
150, 200,
80, 250,
103, 165,
30, 110,
121, 110
];
// 绘制开口五角星
imageopenpolygon($image, $points, count($points) / 2, $starColor);
// 输出图像
header('Content-Type: image/png');
imagepng($image);
// 销毁图像资源
imagedestroy($image);
?>
保存为 star.php 后,在浏览器访问,如:
https://m66.net/star.php
即可看到绘制出来的五角星。
一个简单的雪花可以通过中心对称的放射线条来模拟:
<?php
$image = imagecreatetruecolor(300, 300);
$backgroundColor = imagecolorallocate($image, 255, 255, 255);
$snowColor = imagecolorallocate($image, 0, 0, 255);
imagefill($image, 0, 0, $backgroundColor);
// 雪花中心
$centerX = 150;
$centerY = 150;
$length = 100;
$arms = 6;
// 计算各个点
$points = [];
for ($i = 0; $i < $arms; $i++) {
$angle = deg2rad(360 / $arms * $i);
$x = $centerX + cos($angle) * $length;
$y = $centerY + sin($angle) * $length;
$points[] = $centerX;
$points[] = $centerY;
$points[] = $x;
$points[] = $y;
}
// 绘制雪花
imageopenpolygon($image, $points, count($points) / 2, $snowColor);
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>
保存为 snowflake.php 后,在浏览器访问:
https://m66.net/snowflake.php
就能看到一个放射状的基础雪花结构了!
imageopenpolygon() 是绘制开放式图形的利器,结合数学计算(比如三角函数),你可以创建各种有趣复杂的图形,比如星星、雪花、甚至更加复杂的艺术图案。
如果你想生成更炫酷的复杂图形,可以考虑结合循环逻辑和坐标算法,进一步扩展这种绘制能力!