Erstellen von SolidColorBrush aus einem Hex-Farbwert


129

Ich möchte SolidColorBrush aus einem Hex-Wert wie #ffaacc erstellen. Wie kann ich das machen?

Auf MSDN habe ich:

SolidColorBrush mySolidColorBrush = new SolidColorBrush();
mySolidColorBrush.Color = Color.FromArgb(255, 0, 0, 255);

Also schrieb ich (wenn man bedenkt, dass meine Methode Farbe erhält als #ffaacc):

Color.FromRgb(
  Convert.ToInt32(color.Substring(1, 2), 16), 
  Convert.ToInt32(color.Substring(3, 2), 16), 
  Convert.ToInt32(color.Substring(5, 2), 16));

Aber das gab Fehler als

The best overloaded method match for 'System.Windows.Media.Color.FromRgb(byte, byte, byte)' has some invalid arguments

Auch 3 Fehler als: Cannot convert int to byte.

Aber wie funktioniert dann das MSDN-Beispiel?


6
So dumm, dass sie das Standardformat #FFFFFF nicht zulassen.
MrFox

1
Keine dieser Arbeiten für UWP
kayleeFrye_onDeck

Antworten:


325

Versuchen Sie stattdessen Folgendes:

(SolidColorBrush)(new BrushConverter().ConvertFrom("#ffaacc"));

17

Wie erhalte ich mit .NET Farbe aus hexadezimalem Farbcode?

Ich denke, das ist es, wonach Sie suchen. Ich hoffe, es beantwortet Ihre Frage.

Um Ihren Code zum Laufen zu bringen, verwenden Sie Convert.ToByte anstelle von Convert.ToInt ...

string colour = "#ffaacc";

Color.FromRgb(
Convert.ToByte(colour.Substring(1,2),16),
Convert.ToByte(colour.Substring(3,2),16),
Convert.ToByte(colour.Substring(5,2),16));

15

Ich habe verwendet:

new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ffaacc"));

9
using System.Windows.Media;

byte R = Convert.ToByte(color.Substring(1, 2), 16);
byte G = Convert.ToByte(color.Substring(3, 2), 16);
byte B = Convert.ToByte(color.Substring(5, 2), 16);
SolidColorBrush scb = new SolidColorBrush(Color.FromRgb(R, G, B));
//applying the brush to the background of the existing Button btn:
btn.Background = scb;

4

Wenn Sie nicht jedes Mal mit den Schmerzen der Konvertierung fertig werden möchten, erstellen Sie einfach eine Erweiterungsmethode.

public static class Extensions
{
    public static SolidColorBrush ToBrush(this string HexColorString)
    {
        return (SolidColorBrush)(new BrushConverter().ConvertFrom(HexColorString));
    }    
}

Dann verwenden Sie wie folgt: BackColor = "#FFADD8E6".ToBrush()

Alternativ, wenn Sie eine Methode bereitstellen könnten, um dasselbe zu tun.

public SolidColorBrush BrushFromHex(string hexColorString)
{
    return (SolidColorBrush)(new BrushConverter().ConvertFrom(hexColorString));
}

BackColor = BrushFromHex("#FFADD8E6");

0

vb.net Version

Me.Background = CType(New BrushConverter().ConvertFrom("#ffaacc"), SolidColorBrush)
Durch die Nutzung unserer Website bestätigen Sie, dass Sie unsere Cookie-Richtlinie und Datenschutzrichtlinie gelesen und verstanden haben.
Licensed under cc by-sa 3.0 with attribution required.