Reputation: 15
You know how on YouTube there is a like and dislike bar? But it changes based on proportion (i.e. the bar is always the same size, the green, and red parts just take up different amounts depending on the like/dislike ratio.
I have about a 200x5 space to fill up on a poll page, and I know how to assign, say, 1 pixel per button clicked, but this would be no good if I got only 1 click, or 1,000,000 clicks, as it would look ridiculous on my page. So I need it to be "ratio based" rather than "number based".
Upvotes: 1
Views: 175
Reputation: 27525
Why not just calculate the ratio and multiply it with the number of pixels?
In PHP:
// inputs: $n_likes, $n_dislikes
$bar_width = 200;
$bar_height = 5;
$ratio = $n_likes/($n_likes + $n_dislikes);
$n_green_pixels = round($bar_width * $ratio);
// not even needed: $n_red_pixels = $bar_width - $n_green_pixels;
// create a bar-image:
$bar = imagecreatetruecolor($bar_width, $bar_height);
// fill the whole image with red color:
$red = imagecolorallocate($bar, 255, 0, 0);
imagefilledrectangle($bar, 0, 0, $bar_width-1, $bar_height-1, $red);
if($n_green_pixels > 0)
{
// draw a green line over the red background:
$green = imagecolorallocate($bar, 0, 255, 0);
imagefilledrectangle($bar, 0, 0, $n_green_pixels-1, $bar_height-1, $green);
}
// output the image and perform cleanup:
imagepng($bar); // here: output directly to the browser, include filename as 2nd argument to write to a file
imagedestroy($bar);
Upvotes: 0
Reputation: 15023
Assuming you have $likes (total likes), $votes (total likes + dislikes) and $barWidth (total width of bar in pixels...
First get the ratios:
$likesRatio = $likes/$votes;
So if you have 1 like from 3 votes, this would produce 0.33.
Then multiply by number of pixels:
$likesPixels = $likesRatio * $barWidth;
$dislikesPixels = $barWidth - $likesPixels;
So 0.33 * 200 = 66 pixels, red would be 134 pixels (200 - 66).
Then assign pixels.
Upvotes: 0