百分比到十六进制颜色值

时间:2010-01-26 18:36:28

标签: .net

我可能很难做到这一点,那么从百分比转换为包含RGB十六进制值的一部分的字符串的最简洁方法是什么?

这就是我所拥有的:

//dealing with small percentages, need to magnify the color differences.
double increaseVisibilityFactor = 5;     

double percent = someDouble / someOtherDouble;
double redLightenAmount = 1 - (percent * increaseVisibilityFactor);
if (percent > 0 && redLightenAmount < 0) { redLightenAmount = 0; } //overflow

int increaseWhiteBy = (int)(redLightenAmount * 0xFF);

string hexColor = increaseWhiteBy.ToString("X");
if (hexColor.Length < 2) { hexColor = "0" + hexColor; }
hexColor = "FF" + hexColor + hexColor;

上面的一些行显然可以合并(即转换为int然后转换为字符串),但我想知道是否存在整体缺陷或更好的方法吗?

1 个答案:

答案 0 :(得分:1)

是的,这可以更轻松:

  string hexcolor = string.Format("FF{0:X2}{0:X2}", increaseWhiteBy);