tags:

views:

74

answers:

1

Hi

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 important) tag color (hex code)
+2  A: 

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.

konforce
thanks, but I get a 1 to 3 digit number returned. I think it's because of the 0xff thing.
Alex
You can use `$html_color = sprintf("#%06x", $color);` to convert from an integer 0xff0000 to an HTML color string.
konforce
tx, that works but i get the wrong colors. I think it's because I need to convert $color1 and $color2 from the html color format to the 0xff format
Alex
Alex
Yes, this method should be faster because it minimizes string manipulations. (2 calls to `hexdec`, 1 call to `sprintf`.) Regarding the bitwise operations: each hex digit takes 4 bits. So shifting right by 16 "chops off" the lower 4 digits. The `0xff` is a mask is used to effectively "chop off" everything to the left of the first two digits. So `0xRRGGBB >> 8` == `0xRRGG`. After applying the mask, you get `0xGG` (the green component).
konforce