当前位置: 首页> 最新文章列表> imagefilltoborder 和 imagefilledrectangle 有什么区别?哪个更适合填充图形?

imagefilltoborder 和 imagefilledrectangle 有什么区别?哪个更适合填充图形?

gitbox 2025-05-29

一、函数概述

1. imagefilltoborder()

imagefilltoborder() 的作用是从图像中的某一点开始填充,直到遇到指定边界颜色为止。这类似于油漆桶工具的行为。

函数原型:

bool imagefilltoborder(GdImage $image, int $x, int $y, int $border_color, int $color)
  • $x$y 是起始点坐标;

  • $border_color 是填充的边界颜色;

  • $color 是填充颜色。

这个函数的特点在于“边界触发式填充”。它会从指定坐标出发,将不属于边界颜色的所有像素用填充颜色替换,直到遇到边界为止。

2. imagefilledrectangle()

imagefilledrectangle() 是用来绘制填充的矩形图形的。这个函数更偏向于几何图形的绘制。

函数原型:

bool imagefilledrectangle(GdImage $image, int $x1, int $y1, int $x2, int $y2, int $color)
  • $x1, $y1 是左上角坐标;

  • $x2, $y2 是右下角坐标;

  • $color 是填充颜色。

该函数直接将指定矩形区域内的像素全部用指定颜色填充,无需考虑边界颜色,也不依赖于图像内容的上下文。


二、使用场景对比

功能imagefilltoborderimagefilledrectangle
起始点需指定起点指定坐标区域
填充条件遇到边界颜色即停止仅按坐标矩形填充
灵活性高,可用于不规则图形低,适合规则矩形
性能相对慢(递归搜索)高效
应用场景类似“油漆桶”工具,用于边界填充区域画图、生成图表等结构明确的场景

举例说明:

假设你在创建一个交互式的地图,需要用户点击任意一个区域并填充颜色,那么 imagefilltoborder() 是一个更合适的选择,因为你只需传入点击位置和边界颜色即可。

$image = imagecreatefrompng("https://gitbox.net/images/map.png");
$fill_color = imagecolorallocate($image, 255, 0, 0);
$border_color = imagecolorallocate($image, 0, 0, 0);
imagefilltoborder($image, $x, $y, $border_color, $fill_color);

但如果你要绘制图表中的一个矩形条块,如柱状图中的某一条柱形,那么 imagefilledrectangle() 是更简单直接的选择:

$image = imagecreatetruecolor(200, 100);
$color = imagecolorallocate($image, 0, 128, 255);
imagefilledrectangle($image, 20, 20, 80, 80, $color);

三、哪一个更适合填充图形?

这个问题并没有绝对的答案,而是取决于你的具体需求:

  • 需要从点出发填充不规则区域(如点击后填充轮廓内区域):选择 imagefilltoborder()

  • 需要快速绘制规则几何形状(如图表元素、背景块):使用 imagefilledrectangle() 更合适。

如果你担心性能问题,并且填充图形的形状可以确定,那么优先考虑 imagefilledrectangle()。它的执行速度更快,且不会有意外的边界检测问题。