2010-02-10 83 views
3

我发现下面的函数可以在PHP中绘制垂直渐变。然而,许多网页设计师喜欢他们的渐变具有左上光源,使渐变看起来更真实。那么,如何在垂直渐变上略微改变角度,使其变成轻微的渐变?我不想完全过分,但是它沿着垂直梯度向右进行轻微移动。如何绘制略有对角线的渐变填充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); 

回答

1

下面的代码片段运行速度远远超过了GD库和没有复杂性。不过,您必须安装ImageMagick for PHP。

$oImage = new Imagick(); 
$oImage->newPseudoImage(1000, 400, 'gradient:#09F-#048'); 
$oImage->rotateImage(new ImagickPixel(), -3); 
$oImage->cropImage(960, 250, 25, 100); 
$oImage->setImageFormat('png'); 
header("Content-Type: image/png"); 
echo $oImage; 
1

我不会做几何 - 但创造的垂直梯度较大的图像,然后旋转,裁剪:

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

imagerotate()不适用于我在PHP 5.2.4上。它在php.net页面上说这个函数是GD库函数之一,它有内存泄漏,并且不包含在Ubuntu中(这正是我正在运行的)。有另一种选择? – Volomike 2010-02-10 22:57:43

+0

http://www.php.net/manual/en/function.imagerotate.php#93151 我从来没有使用这个功能 - 但有人发布了一个替代imageRotate函数来解决这个问题,看起来很有前途。 – thetaiko 2010-02-10 23:20:05

+0

我尝试了很多这些,发现imagerotateEquivalent()做了诡计!谢谢,thetaiko。 – Volomike 2010-02-10 23:21:32