web-dev-qa-db-ja.com

16進数の色の値からSolidColorBrushを作成する

#ffaaccなどの16進値からSolidColorBrushを作成したい。これどうやってするの?

MSDNで、私は得た:

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

だから私は書いた(私のメソッドは#ffaaccとして色を受け取ると考える):

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

しかし、これは

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

また、3つのエラー:Cannot convert int to byte.

しかし、MSDNの例はどのように機能しますか?

108
Mahesha999

代わりにこれを試してください:

(SolidColorBrush)(new BrushConverter().ConvertFrom("#ffaacc"));
287
Chris Ray

。NETを使用して16進カラーコードから色を取得する方法?

これはあなたが求めているものだと思う、それがあなたの質問に答えることを望んでいる。

コードを機能させるには、Convert.ToIntではなくConvert.ToByteを使用します...

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));
16
GJHix

私は使用しています:

new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ffaacc"));
13
Jon Vielhaber
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;
9
Mahesha999

変換の苦痛に毎回対処したくない場合は、単に拡張メソッドを作成します。

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

次に、次のように使用します:BackColor = "#FFADD8E6".ToBrush()

2
Neil B