php - 我如何在PHP中绘制略带对角线的渐变填充?

标签 php image gd gradient

我发现以下函数可以在 PHP 中绘制垂直渐变。然而,许多网页设计师喜欢他们的渐变具有左上角的光源,以使渐变看起来更逼真。那么,如何在垂直渐变上稍微改变角度,使其变成微渐变呢?我不想完全过度,只是在垂直梯度下降时向右轻微移动。

<?php

function hex2rgb($sColor) {
    $sColor = str_replace('#','',$sColor);
    $nLen = strlen($sColor) / 3;
    $anRGB = array();
    $anRGB[]=hexdec(str_repeat(substr($sColor,0,$nLen),2/$nLen));
    $anRGB[]=hexdec(str_repeat(substr($sColor,$nLen,$nLen),2/$nLen));
    $anRGB[]=hexdec(str_repeat(substr($sColor,2*$nLen,$nLen),2/$nLen));
    return $anRGB;
}

$nWidth = 960;
$nHeight = 250;
$sStartColor = '#2b8ae1';
$sEndColor = '#0054a1';
$nStep = 1;

$hImage = imagecreatetruecolor($nWidth,$nHeight);
$nRows = imagesy($hImage);
$nCols = imagesx($hImage);
list($r1,$g1,$b1) = hex2rgb($sStartColor);
list($r2,$g2,$b2) = hex2rgb($sEndColor);
$nOld_r = 0; $nOld_g = 0; $nOld_b = 0;
for ( $i = 0; $i < $nRows; $i=$i+1+$nStep ) {
    $r = ( $r2 - $r1 != 0 ) ? intval( $r1 + ( $r2 - $r1 ) * ( $i / $nRows ) ): $r1;
    $g = ( $g2 - $g1 != 0 ) ? intval( $g1 + ( $g2 - $g1 ) * ( $i / $nRows ) ): $g1;
    $b = ( $b2 - $b1 != 0 ) ? intval( $b1 + ( $b2 - $b1 ) * ( $i / $nRows ) ): $b1;
    if ( "$nOld_r,$nOld_g,$nOld_b" != "$r,$g,$b") {
        $hFill = imagecolorallocate( $hImage, $r, $g, $b );
    }
    imagefilledrectangle($hImage, 0, $i, $nCols, $i+$nStep, $hFill);
    $nOld_r= $r;
    $nOld_g= $g;
    $nOld_b= $b;
}
header("Content-type: image/png");
imagepng($hImage);

最佳答案

我不打算做几何图形 - 但将垂直渐变创建为更大的图像,然后旋转并裁剪它:

...
$degrees = -5;
$newImage = imagecreatetruecolor($nWidth, $nHeight);
$rotated = imagerotate($hImage, $degrees, 0);
imagecopy($newImage, $rotated, 0, 0, $x, $y, $width, $height)

关于php - 我如何在PHP中绘制略带对角线的渐变填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2240655/

相关文章:

php - 根据 future 日期自动生成年份

image - 从模型图像中删除包标签

php - base64编码图像而不保存

php - 我应该在 Drupal 中将 ImageMagick 还是 GD2 与 ImageAPI 一起使用?

php - 从数组中删除多个值

php - 在我的新商店 View 中使用我的默认商店中的所有图像

php - 不用sql建表

android - 如何将图像保存到数据库中

PHP图像显示

PHP 函数 imagettftext() 和 unicode