你知道在YouTube上有一个喜欢和不喜欢的酒吧吗? 但它会根据比例而变化(即,条形总是相同的大小,绿色和红色部分只是根据喜欢/不喜欢的比例而占用不同的数量。
我有大约200x5的空间来填充投票页面,我知道如何分配,例如,每个按钮点击1个像素,但如果我只有1次点击,或1,000,000次点击,这将是不好的在我的页面上看起来很荒谬。所以我需要它是“基于比率”而不是“基于数字”。
答案 0 :(得分:0)
假设你有$喜欢(总喜欢),$ votes(总喜欢+不喜欢)和$ barWidth(条形总宽度,以像素为单位......
首先得到比率:
$likesRatio = $likes/$votes;
所以,如果你有3张赞3票,这将产生0.33。
然后乘以像素数:
$likesPixels = $likesRatio * $barWidth;
$dislikesPixels = $barWidth - $likesPixels;
所以0.33 * 200 = 66像素,红色是134像素(200 - 66)。
然后分配像素。
答案 1 :(得分:0)
为什么不计算比率并将其乘以像素数?
在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);