将颜色转换为hexc#

我有转换颜色到hex的问题。 红色下划线低于System.Drawing.ColorTranslator.FromHtml("paint")rect.Color; 可变paint是静态的 – 目前。

在我看来,问题是变量的类型公共System.Drawing.SolidBrush ColorRect类的System.Drawing.SolidBrush Color

  List rects = new List(); rects.Add(new Rect() { Width = x, Height = y, Left = w, Top = h, Fill = (System.Windows.Media.Brush)(new BrushConverter()).ConvertFromString(paint) }); foreach (Rect rect in rects) { Rectangle r = new Rectangle { Width = rect.Width, Height = rect.Width, Fill = rect.Fill }; Canvas.SetLeft(r, rect.Left); Canvas.SetTop(r, rect.Top); canvas.Children.Add(r); } } class Rect { public int Width { get; set; } public int Height { get; set; } public int Left { get; set; } public int Top { get; set; } public System.Windows.Media.Brush Fill { get; set; } } private void rectangle_Click(object sender, RoutedEventArgs e) { choose r1 = new choose(); var paint = "#FFA669D1"; int x = int.Parse(beginx.Text); int y = int.Parse(beginy.Text); int w = int.Parse(wid.Text); int h = int.Parse(hei.Text); if (!((x > canvas.ActualWidth) || (y > canvas.ActualHeight) || (w > canvas.ActualWidth) || (h > canvas.ActualHeight))) { r1.rectangle(x, y, w, h, paint, canvas); } } 

不要将不兼容的WinForms类型System.Drawing.SolidBrush用于WPF矩形的Fill属性。 请改用System.Windows.Media.Brush

 class Rect { ... public Brush Fill { get; set; } } 

然后使用WPF BrushConverter类将hex颜色字符串转换为Brush:

 rect.Fill = (Brush)(new BrushConverter()).ConvertFromString(paint); 

在您的代码示例中,它应如下所示:

 var converter = new BrushConverter(); rects.Add(new Rect { Width = x, Height = y, Left = w, Top = h, Fill = (Brush)converter.ConvertFromString(paint) }); foreach (Rect rect in rects) { Rectangle r = new Rectangle { Width = rect.Width, Height = rect.Width, Fill = rect.Fill }; Canvas.SetLeft(r, rect.Left); Canvas.SetTop(r, rect.Top); canvas.Children.Add(r); }