答案:在 PHP-GD 中使用 imagefilledrectangle() 函数可绘制并填充实心矩形,需指定左上角 (x1, y1) 和右下角 (x2, y2) 坐标,且要求 x2 > x1、y2 > y1。
在 PHP-GD 中填充矩形区域,可以使用 imagefilledrectangle() 函数。这个函数用于绘制并填充实心矩形,与只画边框的 imagerectangle()
不同。
1. 创建图像资源并设置颜色
在绘图前,需要先创建一个图像资源,并定义要用的颜色。
// 创建一个 200x100 的真彩色图像 $im = imagecreatetruecolor(200, 100); // 设置背景色(可选) $bg = imagecolorallocate($im, 255, 255, 255); // 白色 imagefill($im, 0, 0, $bg); // 填充背景 // 定义填充矩形的颜色 $red = imagecolorallocate($im, 255, 0, 0); // 红色
2. 使用 imagefilledrectangle() 填充实心矩形
调用 imagefilledrectangle(),传入图像资源和矩形的两个对角坐标(左上角和右下角)以及颜色索引。
// 绘制从 (50,20) 到 (150,80) 的红色实心矩形 imagefilledrectangle($im, 50, 20, 150, 80, $red);
3. 输出图像并释放内存
最后将图像输出为 PNG 格式,并销毁资源以释放内存。
立即学习“PHP免费学习笔记(深入)”;
完整示例:
<?php $im = imagecreatetruecolor(200, 100); $bg = imagecolorallocate($im, 255, 255, 255); imagefill($im, 0, 0, $bg); $color = imagecolorallocate($im, 0, 128, 255); // 蓝色 imagefilledrectangle($im, 40, 30, 160, 70, $color); header('Content-Type: image/png'); imagepng($im); imagedestroy($im); ?>
基本上就这些。只要确保 GD 扩展已启用,就可以顺利绘制并填充实心矩形。注意坐标的顺序:左上角 x1,y1,右下角 x2,y2,且 x2 > x1,y2 > y1。