我正在尝试使用它来判断颜色是浅色还是深色
Evaluate whether a HEX value is dark or light
现在。它需要一个int
float calcLuminance(int rgb)
{
int r = (rgb & 0xff0000) >> 16;
int g = (rgb & 0xff00) >> 8;
int b = (rgb & 0xff);
return (r*0.299f + g*0.587f + b*0.114f) / 256;
}
虽然我有十六进制颜色。
我尝试这样做
var color = System.Drawing.ColorTranslator.FromHtml("#FFFFFF");
int rgb = color.R + color.G + color.B;
var a = calcLuminance(rgb);
我得到0.11725,我认为它必须在0-256或类似的范围内。
我在做什么错?我是否必须将R
转换为int
?还是我刚刚离开?
只需将十六进制字符串转换为整数:
ways
您可以使用:
int color = Convert.ToInt32("FFFFFF", 16);
public string GenerateRgba(string backgroundColor, decimal backgroundOpacity)
{
Color color = ColorTranslator.FromHtml(hexBackgroundColor);
int r = Convert.ToInt16(color.R);
int g = Convert.ToInt16(color.G);
int b = Convert.ToInt16(color.B);
return string.Format("rgba({0}, {1}, {2}, {3});", r, g, b, backgroundOpacity);
}
主题不多,但这是我创建的Color结构的扩展方法,该结构使用不同的算法来计算亮度。希望对您有帮助。
Link To original Post by jeremy clifton on git
我认为问题是您对public static class ColorExtensions
{
/// <summary>
/// Gets the luminance of the color. A value between 0 (black) and 1 (white)
/// </summary>
/// <param name="color">The color.</param>
/// <param name="algorithm">The type of luminance alg to use.</param>
/// <returns>A value between 0 (black) and 1 (white)</returns>
public static double GetLuminance(this Color color, LuminanceAlgorithm algorithm = LuminanceAlgorithm.Photometric)
{
switch (algorithm)
{
case LuminanceAlgorithm.CCIR601:
return (0.2126 * color.R + 0.7152 * color.G + 0.0722 * color.B) / 255;
case LuminanceAlgorithm.Perceived:
return (Math.Sqrt(0.241 * Math.Pow(color.R, 2) + 0.691 * Math.Pow(color.G, 2) + 0.068 * Math.Pow(color.B, 2)) / 255);
case LuminanceAlgorithm.Photometric:
return (0.299 * color.R + 0.587 * color.G + 0.114 * color.B) / 255;
}
}
/// <summary>
/// The luminances
/// </summary>
public enum LuminanceAlgorithm
{
/// <summary>
/// Photometric/digital ITU-R
/// </summary>
Photometric,
/// <summary>
/// Digital CCIR601 (gives more weight to the R and B components, as preciev by the human eye)
/// </summary>
CCIR601,
/// <summary>
/// A perceived luminance
/// </summary>
Perceived
}
}
的计算。将这些值相加即可得到0到3 * 255之间的数字,这显然不是您的方法所期望的值。您将必须这样计算]
rgb
应与此等效(除了您不使用的Alpha值之外)
int rgb = (int)color.R << 16 + (int)color.G << 8 + color.B;
最后,如您在克里斯·哈斯(Chris Haas)的答案中所见,您可以通过直接转换为整数来跳过此步骤。
[int rgb = color.ToArgb();
仅返回百分比。
您的想法没问题,但您的功能有误,正确的方法在这里:
Color