Nice programing

.NET을 사용하여 16 진수 색상 코드에서 색상을 얻으려면 어떻게합니까?

nicepro 2020. 10. 3. 11:46
반응형

.NET을 사용하여 16 진수 색상 코드에서 색상을 얻으려면 어떻게합니까?


16 진수 색상 코드 (예 :)에서 색상을 얻으려면 어떻게 #FFDFD991해야합니까?

파일을 읽고 있는데 16 진수 색상 코드가 표시됩니다. System.Windows.Media.Color16 진수 색상 코드에 해당하는 인스턴스 를 만들어야합니다 . 이 작업을 수행하는 프레임 워크에 내장 된 메서드가 있습니까?


나는 ... 그는 ARGB 코드입니다 있으리라 믿고있어 당신이 언급하는 System.Drawing.ColorSystem.Windows.Media.Color? 후자는 예를 들어 WPF에서 사용됩니다. 아직 아무도 언급하지 않았으므로 찾고있는 경우를 대비하여 :

using System.Windows.Media;

Color color = (Color)ColorConverter.ConvertFromString("#FFDFD991");

HTML 유형 RGB 코드 (# FFCC66과 같은 16 진수 코드라고 함)를 의미한다고 가정하면 ColorTranslator 클래스를 사용합니다 .

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

그러나 ARGB 16 진수 코드를 사용하는 경우 System.Windows.Media 네임 스페이스에서 ColorConverter 클래스를 사용할 수 있습니다 .

Color col = ColorConverter.ConvertFromString("#FFDFD991") as Color;
//or      = (Color) ColorConverter.ConvertFromString("#FFCC66") ;

ColorTranslator를 사용하지 않으려면 다음에서 쉽게 할 수 있습니다.

string colorcode = "#FFFFFF00";
int argb = Int32.Parse(colorcode.Replace("#", ""), NumberStyles.HexNumber);
Color clr = Color.FromArgb(argb);

색상 코드는 ARGB 값의 16 진수 표현 일뿐입니다.

편집하다

단일 정수 대신 4 개의 값을 사용해야하는 경우 다음을 사용할 수 있습니다 (여러 주석 결합).

string colorcode = "#FFFFFF00";    
colorcode = colorcode.TrimStart('#');

Color col; // from System.Drawing or System.Windows.Media
if (colorcode.Length == 6)
    col = Color.FromArgb(255, // hardcoded opaque
                int.Parse(colorcode.Substring(0,2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(2,2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(4,2), NumberStyles.HexNumber));
else // assuming length of 8
    col = Color.FromArgb(
                int.Parse(colorcode.Substring(0, 2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(2, 2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(4, 2), NumberStyles.HexNumber),
                int.Parse(colorcode.Substring(6, 2), NumberStyles.HexNumber));

참고 1 : NumberStyles는 System.Globalization에 있습니다.
참고 2 : 자체 오류 검사를 제공하십시오 (색상 코드는 6 또는 8 자의 16 진수 값이어야합니다).


이 깔끔한 확장 방법도 있습니다.

static class ExtensionMethods
{
    public static Color ToColor(this uint argb)
    {
        return Color.FromArgb((byte)((argb & -16777216)>> 0x18),      
                              (byte)((argb & 0xff0000)>> 0x10),   
                              (byte)((argb & 0xff00) >> 8),
                              (byte)(argb & 0xff));
    }
}

사용:

Color color = 0xFFDFD991.ToColor();

The three variants below give exactly the same color. The last one has the benefit of being highlighted in the Visual Studio 2010 IDE (maybe it's ReSharper that's doing it) with proper color.

var cc1 = System.Drawing.ColorTranslator.FromHtml("#479DEE");

var cc2 = System.Drawing.Color.FromArgb(0x479DEE);

var cc3 = System.Drawing.Color.FromArgb(0x47, 0x9D, 0xEE);

    private Color FromHex(string hex)
    {
        if (hex.StartsWith("#"))
            hex = hex.Substring(1);

        if (hex.Length != 6) throw new Exception("Color not valid");

        return Color.FromArgb(
            int.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
            int.Parse(hex.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
            int.Parse(hex.Substring(4, 2), System.Globalization.NumberStyles.HexNumber));
    }

You could use the following code:

Color color = System.Drawing.ColorTranslator.FromHtml("#FFDFD991");

I needed to convert a HEX color code to a System.Drawing.Color, specifically a shade of Alice Blue as a background on a WPF form and found it took longer than expected to find the answer:

using System.Windows.Media;

--

System.Drawing.Color myColor = System.Drawing.ColorTranslator.FromHtml("#EFF3F7");
this.Background = new SolidColorBrush(System.Windows.Media.Color.FromArgb(myColor.A, myColor.R, myColor.G, myColor.B));

If you want to do it with a Windows Store App, following by @Hans Kesting and @Jink answer:

    string colorcode = "#FFEEDDCC";
    int argb = Int32.Parse(colorcode.Replace("#", ""), NumberStyles.HexNumber);
    tData.DefaultData = Color.FromArgb((byte)((argb & -16777216) >> 0x18),
                          (byte)((argb & 0xff0000) >> 0x10),
                          (byte)((argb & 0xff00) >> 8),
                          (byte)(argb & 0xff));

This post has become the goto for anyone trying to convert from a hex color code to a system color. Therefore, I thought I'd add a comprehensive solution that deals with both 6 digit (RGB) and 8 digit (ARGB) hex values.

By default, according to Microsoft, when converting from an RGB to ARGB value

The alpha value is implicitly 255 (fully opaque).

This means by adding FF to a 6 digit (RGB) hex color code it becomes an 8 digit ARGB hex color code. Therefore, a simple method can be created that handles both ARGB and RGB hex's and converts them to the appropriate Color struct.

    public static System.Drawing.Color GetColorFromHexValue(string hex)
    {
        string cleanHex = hex.Replace("0x", "").TrimStart('#');

        if (cleanHex.Length == 6)
        {
            //Affix fully opaque alpha hex value of FF (225)
            cleanHex = "FF" + cleanHex;
        }

        int argb;

        if (Int32.TryParse(cleanHex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out argb))
        {
            return System.Drawing.Color.FromArgb(argb);
        }

        //If method hasn't returned a color yet, then there's a problem
        throw new ArgumentException("Invalid Hex value. Hex must be either an ARGB (8 digits) or RGB (6 digits)");

    }

This was inspired by Hans Kesting's answer.


You can see Silverlight/WPF sets ellipse with hexadecimal colour for using a hex value:

your_contorl.Color = DirectCast(ColorConverter.ConvertFromString("#D8E0A627"), Color)

WPF:

using System.Windows.Media;

//hex to color
Color color = (Color)ColorConverter.ConvertFromString("#7AFF7A7A");

//color to hex
string hexcolor = color.ToString();

Use

System.Drawing.Color.FromArgb(myHashCode);

If you mean HashCode as in .GetHashCode(), I'm afraid you can't go back. Hash functions are not bi-directional, you can go 'forward' only, not back.

Follow Oded's suggestion if you need to get the color based on the hexadecimal value of the color.


The most basic is simply:

Color.ParseColor("#ff43a047")

참고URL : https://stackoverflow.com/questions/2109756/how-do-i-get-the-color-from-a-hexadecimal-color-code-using-net

반응형