【问题标题】:Making a "like bar" using ratio not individual inputs?使用比率而不是单个输入来制作“like bar”?
【发布时间】:2013-04-12 14:21:54
【问题描述】:
您知道 YouTube 上有一个喜欢和不喜欢的栏吗?
但它会根据比例而变化(即条形始终大小相同,绿色和红色部分只是根据喜欢/不喜欢的比例占据不同的数量。
我在投票页面上有大约 200x5 的空间可以填充,并且我知道如何分配,例如,每个按钮单击 1 个像素,但如果我只有 1 次单击或 1,000,000 次单击,这将是不好的,因为在我的页面上看起来很荒谬。所以我需要它是“基于比率”而不是“基于数字”。
【问题讨论】:
标签:
php
output
social-media-like
【解决方案1】:
假设您有 $likes(总喜欢)、$votes(总喜欢 + 不喜欢)和 $barWidth(条形的总宽度,以像素为单位...
首先得到比率:
$likesRatio = $likes/$votes;
因此,如果您从 3 票中获得 1 个赞,则将产生 0.33。
然后乘以像素数:
$likesPixels = $likesRatio * $barWidth;
$dislikesPixels = $barWidth - $likesPixels;
所以 0.33 * 200 = 66 像素,红色将是 134 像素 (200 - 66)。
然后分配像素。
【解决方案2】:
为什么不直接计算比率并将其乘以像素数?
在 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);