當前位置: 首頁> 最新文章列表> 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是填充顏色。

該函數直接將指定矩形區域內的像素全部用指定顏色填充,無需考慮邊界顏色,也不依賴於圖像內容的上下文。


二、使用場景對比

功能imagefilltoborder imagefilledrectangle
起始點需指定起點指定坐標區域
填充條件遇到邊界顏色即停止僅按坐標矩形填充
靈活性高,可用於不規則圖形低,適合規則矩形
性能相對慢(遞歸搜索)高效
應用場景類似“油漆桶”工具,用於邊界填充區域畫圖、生成圖表等結構明確的場景

舉例說明:

假設你在創建一個交互式的地圖,需要用戶點擊任意一個區域並填充顏色,那麼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() 。它的執行速度更快,且不會有意外的邊界檢測問題。