gpt4 book ai didi

c# - 以编程方式从 Brushes 类中获取画笔?

转载 作者:太空狗 更新时间:2023-10-29 22:52:23 24 4
gpt4 key购买 nike

我有一个属性允许将已知颜色的字符串名称发送到我的控件。该属性只接受正确的已知颜色名称,如“红色”或“蓝色”

  private KnownColor _UseColor = KnownColor.Red;

/// <summary>
/// Gets or sets the name of the colour
/// </summary>
public string ColorName
{
get
{
return this._UseColor.ToString();
}
set
{
if (Enum.IsDefined(typeof(KnownColor), value))
this._UseColour = (KnownColor)Enum.Parse(typeof(KnownColor), value);
}
}

我想做的是使用此 _UseColour 枚举从静态 Brushes 中选择一个现有画笔像这样在 .NET 中上课

Brush sysBrush = Brushes.FromKnownColor(this._UseColor);
e.Graphics.FillRectangle(sysBrush, 0, 0, 10, 10);

而不是每当像这样绘制控件时都创建一个新画笔

using (SolidBrush brsh = new SolidBrush(Color.FromKnownColor(this._UseColor)))
e.Graphics.FillRectangle(brsh, 0, 0, 10, 10);

有谁知道这是否可行,或者我每次都必须创建一个新画笔吗?

Brushes.FromKnownColor 不是 Brushes 类中的方法

最佳答案

为什么不创建一次画笔并将其缓存以备后用?

在你的主类中:

private KnownColor _UseColor = KnownColor.Red;

/// <summary>
/// Gets or sets the name of the colour
/// </summary>
public string ColorName
{
get
{
return this._UseColor.ToString();
}
set
{
if (Enum.IsDefined(typeof(KnownColor), value))
this._UseColour = (KnownColor)Enum.Parse(typeof(KnownColor), value);
}
}

private Dictionary<string, Brush> _knownBrushes = new Dictionary<string, Brush>();

public Brush ColorBrush
{
get
{
if (!_knownBrushes.ContainsKey(_UseColor)) {
_knownBrushes[_UseColor] = new SolidBrush(Color.FromKnownColor(this._UseColor));
}

return _knownBrushes[_UseColor];
}
}

然后像...一样使用它

e.Graphics.FillRectangle(ColorBrush, 0, 0, 10, 10);

关于c# - 以编程方式从 Brushes 类中获取画笔?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15134113/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com