使用imagefilledellipse()可绘制填充实心椭圆,需先创建图像资源并分配颜色,调用函数时指定中心点、直径和填充色,最后输出图像并释放资源。
在 PHP 中使用 GD 库绘制并填充实心椭圆区域,可以通过 imagefilledellipse() 函数直接实现。这个函数会根据指定的中心点、宽高和颜色,绘制一个被填充的椭圆形。
1. 创建图像资源并设置颜色
开始前需要创建一个图像资源,并分配用于填充的颜色。
- $image = imagecreatetruecolor(400, 300); // 创建 400x300 的画布
- $bgColor = imagecolorallocate($image, 255, 255, 255); // 白色背景
- imagefill($image, 0, 0, $bgColor); // 填充背景
- $fillColor = imagecolorallocate($image, 0, 128, 255); // 蓝色用于椭圆填充
2. 使用 imagefilledellipse() 填充实心椭圆
调用该函数,传入中心坐标、宽度、高度和颜色即可。
- imagefilledellipse($image, 200, 150, 300, 180, $fillColor);
参数说明:
立即学习“PHP免费学习笔记(深入)”;
- 200, 150:椭圆中心点 x 和 y 坐标
- 300:椭圆总宽度(横轴直径)
- 180:椭圆总高度(纵轴直径)
- $fillColor:填充颜色资源
3. 输出图像并释放资源
将结果输出为 PNG 图像,并销毁资源以释放内存。
- header("Content-Type: image/png");
- imagepng($image); // 输出图像
- imagedestroy($image); // 释放资源
完整示例代码:
$image = imagecreatetruecolor(400, 300); $bgColor = imagecolorallocate($image, 255, 255, 255); imagefill($image, 0, 0, $bgColor); $fillColor = imagecolorallocate($image, 0, 128, 255); imagefilledellipse($image, 200, 150, 300, 180, $fillColor); header("Content-Type: image/png"); imagepng($image); imagedestroy($image);
基本上就这些。只要确保 GD 扩展已启用,imagefilledellipse() 就能轻松绘制出填充实心的椭圆区域。不复杂但容易忽略的是:宽高指的是整个椭圆的直径,不是半径。