【问题标题】:Getting the name of color through Hex Value?通过十六进制值获取颜色名称?
【发布时间】:2012-07-29 16:25:36
【问题描述】:

我知道如何使用十六进制值获取预定义颜色的名称,但如何在将其十六进制值近似为最接近的已知颜色时获取颜色名称。

【问题讨论】:

    标签: c# colors


    【解决方案1】:

    这是基于 Ian 建议的一些代码。我在一些颜色值上对其进行了测试,似乎效果很好。

    GetApproximateColorName(ColorTranslator.FromHtml(source))
    
    private static readonly IEnumerable<PropertyInfo> _colorProperties = 
                typeof(Color)
                .GetProperties(BindingFlags.Public | BindingFlags.Static)
                .Where(p => p.PropertyType == typeof (Color));
    
    static string GetApproximateColorName(Color color)
    {
        int minDistance = int.MaxValue;
        string minColor = Color.Black.Name;
    
        foreach (var colorProperty in _colorProperties)
        {
            var colorPropertyValue = (Color)colorProperty.GetValue(null, null);
            if (colorPropertyValue.R == color.R
                    && colorPropertyValue.G == color.G
                    && colorPropertyValue.B == color.B)
            {
                return colorPropertyValue.Name;
            }
    
            int distance = Math.Abs(colorPropertyValue.R - color.R) +
                            Math.Abs(colorPropertyValue.G - color.G) +
                            Math.Abs(colorPropertyValue.B - color.B);
    
            if (distance < minDistance)
            {
                minDistance = distance;
                minColor = colorPropertyValue.Name;
            }
        }
    
        return minColor;
    }
    

    【讨论】:

      【解决方案2】:

      https://stackoverflow.com/a/7792104/224370 解释了如何将命名颜色与精确的 RGB 值匹配。为了使其近似,您需要某种距离函数来计算颜色之间的距离。在 RGB 空间中执行此操作(R、G 和 B 值的平方和)不会给您一个完美的答案(但可能已经足够好了)。请参阅https://stackoverflow.com/a/7792111/224370 以获取这样做的示例。要获得更准确的答案,您可能需要转换为 HSL,然后进行比较。

      【讨论】:

        猜你喜欢
        • 2015-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-04
        • 1970-01-01
        • 2016-05-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多