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

Mak*_*kla 3 colors asp.net-core

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

ColorSystem.Drawing名称空间中找到了类,但是没有合适的方法FromHex

我需要将值转换为:

#F3A
#2F3682
#83A7B278
Run Code Online (Sandbox Code Playgroud)

Leo*_*nid 6

我发现corefx包含System.Drawing.Common,所以你可以使用

Color col = ColorTranslator.FromHtml("#FFCC66");
Run Code Online (Sandbox Code Playgroud)

源代码可以在这里找到:GitHub


Mak*_*kla 5

我没有找到可以处理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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用例:

ColorManager.FromHex("#C3B271");
ColorManager.FromHex("#CCC");
ColorManager.FromHex("#C3B27144");
ColorManager.FromHex("#C3B27144", out var a, out var r, out var g, out var b);
Run Code Online (Sandbox Code Playgroud)

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