1

你知道 YouTube 上有一个喜欢和不喜欢的栏吗?但它会根据比例而变化(即,条形始终大小相同,绿色和红色部分只是根据喜欢/不喜欢的比例占据不同的数量。

我在投票页面上有大约 200x5 的空间可以填充,并且我知道如何分配,例如,每个按钮单击 1 个像素,但是如果我只有 1 次单击或 1,000,000 次单击,这将是不好的,因为它看起来在我的页面上很可笑。所以我需要它是“基于比率的”而不是“基于数字的”。

4

2 回答 2

0

假设您有 $likes(总喜欢)、$votes(总喜欢 + 不喜欢)和 $barWidth(条形的总宽度,以像素为单位...

首先得到比率:

$likesRatio = $likes/$votes;

因此,如果您从 3 票中获得 1 个赞,这将产生 0.33。

然后乘以像素数:

$likesPixels = $likesRatio * $barWidth;
$dislikesPixels = $barWidth - $likesPixels;

所以 0.33 * 200 = 66 像素,红色将是 134 像素 (200 - 66)。

然后分配像素。

于 2013-04-19T08:35:09.830 回答
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); 
于 2013-04-19T08:35:30.647 回答