如何在 PHP 中绘制渐变矩形?

tho*_*olu -4 php drawing gd

我想画这样的双渐变 坡度 在 PHP 中(不同颜色)。

编辑:最终修改答案中提供的渐变函数之一以简单地绘制双渐变。

Har*_*jan 6

使用普通的 GD Image 函数在 PHP 中创建渐变。该函数对颜色值使用 HTML 十六进制代码,然后将它们转换为具有 RGB 值的数组。

function image_gradientrect($img,$x,$y,$x1,$y1,$start,$end) {
   if($x > $x1 || $y > $y1) {
      return false;
   }
   $s = array(
      hexdec(substr($start,0,2)),
      hexdec(substr($start,2,2)),
      hexdec(substr($start,4,2))
   );
   $e = array(
      hexdec(substr($end,0,2)),
      hexdec(substr($end,2,2)),
      hexdec(substr($end,4,2))
   );
   $steps = $y1 - $y;
   for($i = 0; $i < $steps; $i++) {
      $r = $s[0] - ((($s[0]-$e[0])/$steps)*$i);
      $g = $s[1] - ((($s[1]-$e[1])/$steps)*$i);
      $b = $s[2] - ((($s[2]-$e[2])/$steps)*$i);
      $color = imagecolorallocate($img,$r,$g,$b);
      imagefilledrectangle($img,$x,$y+$i,$x1,$y+$i+1,$color);
   }
   return true;
}


$imgWidth = 300;
$imgHeight = 150;
$img = imagecreatetruecolor($imgWidth,$imgHeight);

image_gradientrect($img,0,0,$imgWidth,$imgHeight,'ff0000','0000ff');
/* Show In Browser as Image */
header('Content-Type: image/png');
imagepng($img);

/* Save as a File */
imagepng($img,'save.png');

/* Some Cleanup */
imagedestroy($img);
Run Code Online (Sandbox Code Playgroud)

只需在上面的代码中更改高度、宽度和颜色,它就会生成矩形图像。