2010-02-10 109 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