开发者

PHP - calculate color (hex) based on given variables

I'm trying to create a tag cloud and need help in creating a function that can calculate the color needed to apply to each tag link.

I have 3 variables:

  • individual tag importance (from 0.1 to 1)
  • largest (most important) tag color (hex code, eg. 'fff000')
  • (hex code) smallest (less import开发者_StackOverflowant) tag color (hex code)


Here's some stuff to get you started:

You can get the r,g,b values via:

$color1 = 0xfff000;
$r1 = ($color1 >> 16) & 0xff;
$g1 = ($color1 >> 8) & 0xff;
$b1 = $color1 & 0xff;

To interpolate between two values:

define('MIN', 0.10);
define('MAX', 1.00);
define('RANGE', MAX - MIN);

$i = 0.10; // importance

$i = ($i - MIN) / RANGE;

$r = $r1 + ($r2 - $r1) * $i;
$g = $g1 + ($g2 - $g1) * $i;
$b = $b1 + ($b2 - $b1) * $i;

Then you can put them back:

$color = ($r << 16) | ($g << 8) | $b;

But RGB isn't necessarily the best color space to work with. You might get better results by using something like HSL.

Alternatively to all of this, you could simply create 10 colors by hand that you like, and put them into an array:

$colors = array('#000000', '#100000', ... );
$color = $colors[intval(($importance - 0.10) / 0.0901)];

The 0.0901 number is simply (MAX - MIN) / 10 + smallDelta. The delta is used to keep the maximum index at 9 (instead of 10) for when $importance == MAX.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜