答案:在 PHP-GD 中使用 imagefilledrectangle() 函数可绘制并填充实心矩形,需指定左上角 (x1, y1) 和右下角 (x2, y2) 坐标,且要求 x2 > x1、y2 > y1。

在 PHP-GD 中填充矩形区域,可以使用 imagefilledrectangle() 函数。这个函数用于绘制并填充实心矩形,与只画边框的 imagerectangle() 不同。
在绘图前,需要先创建一个图像资源,并定义要用的颜色。
// 创建一个 200x100 的真彩色图像 $im = imagecreatetruecolor(200, 100); // 设置背景色(可选) $bg = imagecolorallocate($im, 255, 255, 255); // 白色 imagefill($im, 0, 0, $bg); // 填充背景 // 定义填充矩形的颜色 $red = imagecolorallocate($im, 255, 0, 0); // 红色
调用 imagefilledrectangle(),传入图像资源和矩形的两个对角坐标(左上角和右下角)以及颜色索引。
// 绘制从 (50,20) 到 (150,80) 的红色实心矩形 imagefilledrectangle($im, 50, 20, 150, 80, $red);
最后将图像输出为 PNG 格式,并销毁资源以释放内存。
立即学习“PHP免费学习笔记(深入)”;
// 输出图像到浏览器
header('Content-Type: image/png');
imagepng($im);
// 释放内存
imagedestroy($im);
完整示例:
<?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。
以上就是php-gd怎么填充矩形_php-gd填充实心矩形区域的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号