Translate color to hexadecimal c#

六月ゝ 毕业季﹏ 提交于 2020-01-11 14:30:24

问题


I have problem with conversion color to hexadecimal. Red underline is below System.Drawing.ColorTranslator.FromHtml("paint") and rect.Color; Variable paint is static - for now.

In my opinion the problem is in variable's type public System.Drawing.SolidBrush Color at Rect class

 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);
    }
}

回答1:


Do not use the incompatible WinForms type System.Drawing.SolidBrush for the Fill property of a WPF Rectangle. Use System.Windows.Media.Brush instead:

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

Then use the WPF BrushConverter class to convert a hexadecimal color string to a Brush:

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

In your code sample, it should look like this:

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);
}


来源:https://stackoverflow.com/questions/44244232/translate-color-to-hexadecimal-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!