条件格式——颜色转换的百分比 [英] Conditional formatting -- percentage to color conversion
问题描述
将百分比转换为从绿色 (100%) 到红色 (0%) 以及黄色为 50% 的颜色的最简单方法是什么?
我使用的是普通的 32 位 RGB - 所以每个分量都是 0 到 255 之间的一个整数.我在 C# 中这样做,但我想对于这样的问题,语言并不重要.>
根据 Marius 和 Andy 的回答,我使用了以下解决方案:
double red = (percent <50) ?255 : 256 - (百分比 - 50) * 5.12;双绿色=(百分比> 50)?255:百分比 * 5.12;var color = Color.FromArgb(255, (byte)red, (byte)green, 0);
完美运行 - 我必须从 Marius 解决方案中进行的唯一调整是使用 256,如 (255 - (percent - 50) * 5.12 yield -1 when 100%,由于某种原因导致 Silverlight 中的黄色 (-1,255, 0) -> 黄色 ...
我用 JavaScript 创建了这个函数.它返回的颜色是一个 css 字符串.它将百分比作为一个变量,范围从 0 到 100.该算法可以用任何语言编写:
function setColor(p){var red = p<50 ?255 : Math.round(256 - (p-50)*5.12);var green = p>50 ?255:Math.round((p)*5.12);return "rgb(" + red + "," + green + ",0)";}
What's the easiest way to convert a percentage to a color ranging from Green (100%) to Red (0%), with Yellow for 50%?
I'm using plain 32bit RGB - so each component is an integer between 0 and 255. I'm doing this in C#, but I guess for a problem like this the language doesn't really matter that much.
Based on Marius and Andy's answers I'm using the following solution:
double red = (percent < 50) ? 255 : 256 - (percent - 50) * 5.12;
double green = (percent > 50) ? 255 : percent * 5.12;
var color = Color.FromArgb(255, (byte)red, (byte)green, 0);
Works perfectly - Only adjustment I had to make from Marius solution was to use 256, as (255 - (percent - 50) * 5.12 yield -1 when 100%, resulting in Yellow for some reason in Silverlight (-1, 255, 0) -> Yellow ...
I made this function in JavaScript. It returns the color is a css string. It takes the percentage as a variable, with a range from 0 to 100. The algorithm could be made in any language:
function setColor(p){
var red = p<50 ? 255 : Math.round(256 - (p-50)*5.12);
var green = p>50 ? 255 : Math.round((p)*5.12);
return "rgb(" + red + "," + green + ",0)";
}
这篇关于条件格式——颜色转换的百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!