PHP Conference Japan 2024

imagerectangle

(PHP 4, PHP 5, PHP 7, PHP 8)

imagerectangle繪製矩形

描述

imagerectangle(
    GdImage $image,
    int $x1,
    int $y1,
    int $x2,
    int $y2,
    int $color
): bool

imagerectangle() 從指定的座標開始建立一個矩形。

參數

image

一個 GdImage 物件,由其中一個影像建立函式返回,例如 imagecreatetruecolor()

x1

左上角 x 座標。

y1

左上角 y 座標,0, 0 是影像的左上角。

x2

右下角 x 座標。

y2

右下角 y 座標。

color

使用 imagecolorallocate() 建立的顏色識別碼。

返回值

成功時返回 true,失敗時返回 false

更新日誌

版本 描述
8.0.0 image 現在需要一個 GdImage 實例;先前需要一個有效的 gd 資源

範例

範例 #1 簡單的 imagerectangle() 範例

<?php
// 建立一個 200 x 200 的影像
$canvas = imagecreatetruecolor(200, 200);

// 配置顏色
$pink = imagecolorallocate($canvas, 255, 105, 180);
$white = imagecolorallocate($canvas, 255, 255, 255);
$green = imagecolorallocate($canvas, 132, 135, 28);

// 繪製三個各自使用不同顏色的矩形
imagerectangle($canvas, 50, 50, 150, 150, $pink);
imagerectangle($canvas, 45, 60, 120, 100, $white);
imagerectangle($canvas, 100, 120, 75, 160, $green);

// 輸出並從記憶體中釋放
header('Content-Type: image/jpeg');

imagejpeg($canvas);
imagedestroy($canvas);
?>

上述範例將輸出類似以下的內容

Output of example : Simple imagerectangle() example

新增註釋

使用者貢獻的筆記 3 則筆記

stanislav dot eckert at vizson dot de
9 年前
如果您想要繪製像素完美的矩形,請注意:由於此函式使用絕對值作為第二個座標點(而不是寬度和高度),您可能會遇到邏輯問題。PHP 從 0 開始計數。但是位於 0,0 位置的像素已經佔用了 1x1 的空間。在上面的範例中,您有以下這一行:

imagerectangle($canvas, 50, 50, 150, 150, $pink);

如果您沒有注意到這一點,您可能會認為兩個座標之間的差值正好是 100,並假設繪製的矩形尺寸也是 100 x 100 像素。但它會是 101 x 101,因為 PHP 從 0 開始計數,而且 imagerectangle() 也使用絕對座標作為第二個點。一個更小的例子:座標為 0,0 和 5,5 的矩形表示 0,1,2,3,4,5,這是 6 個像素,而不是 5 個。
eustaquiorangel at yahoo dot com
21 年前
如果您想要一個空的矩形,也就是只有邊框,請先使用 ImageFilledRectangle 函式以背景顏色填充它,然後再使用此函式繪製它。
rogier
17 年前
除了 Corey 的筆記之外,這就是他所指的程式碼類型。請注意,我總是繪製一個外部網格邊框,因此繪製線條總是需要
1 + ceil((rows+cols)/2) 個動作。對於 20X20 的網格,這表示 21 個動作,而 10X25 的網格則需要 19 個動作

<?php

function draw_grid(&$img, $x0, $y0, $width, $height, $cols, $rows, $color) {
//draw outer border
imagerectangle($img, $x0, $y0, $x0+$width*$cols, $y0+$height*$rows, $color);
//first draw horizontal
$x1 = $x0;
$x2 = $x0 + $cols*$width;
for (
$n=0; $n<ceil($rows/2); $n++) {
$y1 = $y0 + 2*$n*$height;
$y2 = $y0 + (2*$n+1)*$height;
imagerectangle($img, $x1,$y1,$x2,$y2, $color);
}
//then draw vertical
$y1 = $y0;
$y2 = $y0 + $rows*$height;
for (
$n=0; $n<ceil($cols/2); $n++) {
$x1 = $x0 + 2*$n*$width;
$x2 = $x0 + (2*$n+1)*$width;
imagerectangle($img, $x1,$y1,$x2,$y2, $color);
}
}

//example
$img = imagecreatetruecolor(300, 200);
$red = imagecolorallocate($img, 255, 0, 0);
draw_grid($img, 0,0,15,20,20,10,$red);
header("Content-type: image/png");
imagepng($img);
imagedestroy($img);
?>
have fun ;)
To Top