从ASP.NET Core中的十六进制获取颜色

时间:2018-01-09 17:10:45

标签: asp.net-core colors

如何从ASP.NET Core中的十六进制值获取Color

我在Color命名空间中找到了System.Drawing类,但没有找到合适的方法FromHex

我需要转换像:

这样的值
#F3A
#2F3682
#83A7B278

2 个答案:

答案 0 :(得分:4)

我没有找到能处理alpha的库,所以我自己编写。

using System;
using System.Drawing;
using System.Globalization;

namespace Color.Library
{
    public class ColorManager
    {
        public static Color FromHex(string hex)
        {
            FromHex(hex, out var a, out var r, out var g, out var b);

            return Color.FromArgb(a, r, g, b);
        }

        public static void FromHex(string hex, out byte a, out byte r, out byte g, out byte b)
        {
            hex = ToRgbaHex(hex);
            if (hex == null || !uint.TryParse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var packedValue))
            {
                throw new ArgumentException("Hexadecimal string is not in the correct format.", nameof(hex));
            }

            a = (byte) (packedValue >> 0);
            r = (byte) (packedValue >> 24);
            g = (byte) (packedValue >> 16);
            b = (byte) (packedValue >> 8);
        }


        private static string ToRgbaHex(string hex)
        {
            hex = hex.StartsWith("#") ? hex.Substring(1) : hex;

            if (hex.Length == 8)
            {
                return hex;
            }

            if (hex.Length == 6)
            {
                return hex + "FF";
            }

            if (hex.Length < 3 || hex.Length > 4)
            {
                return null;
            }

            //Handle values like #3B2
            string red = char.ToString(hex[0]);
            string green = char.ToString(hex[1]);
            string blue = char.ToString(hex[2]);
            string alpha = hex.Length == 3 ? "F" : char.ToString(hex[3]);


            return string.Concat(red, red, green, green, blue, blue, alpha, alpha);
        }
    }
}

用例:

ColorManager.FromHex("#C3B271");
ColorManager.FromHex("#CCC");
ColorManager.FromHex("#C3B27144");
ColorManager.FromHex("#C3B27144", out var a, out var r, out var g, out var b);

我从ImageSharp库中借用了大部分代码。

答案 1 :(得分:3)

我发现corefx包含System.Drawing.Common,因此您可以使用

Color col = ColorTranslator.FromHtml("#FFCC66");

可在此处找到源代码:GitHub