[英]Translate color to hexadecimal c#
我將顏色轉換為十六進制時遇到問題。 紅色下划線位於System.Drawing.ColorTranslator.FromHtml("paint")
和rect.Color;
可變paint
是靜態的-現在。
我認為問題出在Rect
類的變量類型為public System.Drawing.SolidBrush Color
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);
}
}
不要對WPF矩形的Fill
屬性使用不兼容的WinForms類型System.Drawing.SolidBrush
。 使用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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.