`

【代码片段】取最接近的Web-Safe Color

阅读更多
作者: RayLinn

最近的项目里需要从索引颜色里取最接近的颜色,用下面的代码实现之:

        public static Color ScanNearestColor(Color color)
        {
            int leastDistance = int.MaxValue;
            int red = color.R;
            int green = color.G;
            int blue = color.B;
            byte colorIndex = 255;
            Color[] _colors = GetColorPalette();
            for (int index = 0; index < _colors.Length; index++)
            {
                // Lookup the color from the palette
                Color paletteColor = _colors[index];

                // Compute the distance from our source color to the palette color
                int redDistance = paletteColor.R - red;
                int greenDistance = paletteColor.G - green;
                int blueDistance = paletteColor.B - blue;

                int distance = (redDistance * redDistance) +
                                    (greenDistance * greenDistance) +
                                    (blueDistance * blueDistance);

                // If the color is closer than any other found so far, use it
                if (distance < leastDistance)
                {
                    colorIndex = (byte)index;
                    leastDistance = distance;

                    // And if it's an exact match, exit the loop
                    if (0 == distance)
                        break;
                }
            }
            return _colors[colorIndex];
        }


代码里的GetColorPalette返回索引颜色表,比如下面是生成Web安全色的颜色表:
        private static Color[] GetWebSafeColorPalette()
        {
            Color[] aSafeCols = new Color[216];
            int rValue, gValue, bValue;
            int iPointer = 0;
            for (rValue = 0; rValue <= 255; rValue += 51)
            {
                for (gValue = 0; gValue <= 255; gValue += 51)
                {
                    for (bValue = 0; bValue <= 255; bValue += 51)
                    {
                        aSafeCols[iPointer] = Color.FromRgb((byte)rValue,(byte)gValue,(byte)bValue);
                        iPointer += 1;
                    }
                }
            }


基本最后完成的是个基于Visual studio的CSS编辑器,配上上个项目里为CSS的颜色定义添加相应颜色的下划线,这样的CSS编辑器相当不错了,如果要完美一点,还可以加上图片预览的功能。



参考:
http://msdn.microsoft.com/en-us/library/aa479306.aspx
  • 大小: 241.2 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics