我有转换颜色到十六进制的问题。红色下划线低于System.Drawing.ColorTranslator.FromHtml("paint")
和rect.Color;
变量paint
目前是静态的。
在我看来,问题出现在System.Drawing.SolidBrush Color
类的变量类型public Rect
List<Rect> rects = new List<Rect>();
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);
}
}
答案 0 :(得分:1)
不要将不兼容的WinForms类型System.Drawing.SolidBrush
用于WPF矩形的Fill
属性。请改用System.Windows.Media.Brush
:
class Rect
{
...
public Brush Fill { get; set; }
}
然后使用WPF BrushConverter
类将十六进制颜色字符串转换为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);
}