C# Brush to string

偶尔善良 提交于 2019-11-27 04:51:57

问题


I search a way to save the color of a brush as a string. For example I have a Brush which has the color red. Now I want to write "red" in a textbox.

Thanks for any help.


回答1:


If the Brush was created using a Color from System.Drawing.Color, then you can use the Color's Name property.

Otherwise, you could just try to look up the color using reflection

// hack
var b = new SolidBrush(System.Drawing.Color.FromArgb(255, 255, 235, 205));
var colorname = (from p in typeof(System.Drawing.Color).GetProperties()
                 where p.PropertyType.Equals(typeof(System.Drawing.Color))
                 let value = (System.Drawing.Color)p.GetValue(null, null)
                 where value.R == b.Color.R &&
                       value.G == b.Color.G &&
                       value.B == b.Color.B &&
                       value.A == b.Color.A
                 select p.Name).DefaultIfEmpty("unknown").First();

// colorname == "BlanchedAlmond"

or create a mapping yourself (and look the color up via a Dictionary), probably using one of many color tables around.

Edit:

You wrote a comment saying you use System.Windows.Media.Color, but you could still use System.Drawing.Color to look up the name of the color.

var b = System.Windows.Media.Color.FromArgb(255, 255, 235, 205);
var colorname = (from p in typeof(System.Drawing.Color).GetProperties()
                 where p.PropertyType.Equals(typeof(System.Drawing.Color))
                 let value = (System.Drawing.Color)p.GetValue(null, null)
                 where value.R == b.R &&
                       value.G == b.G &&
                       value.B == b.B &&
                       value.A == b.A
                 select p.Name).DefaultIfEmpty("unknown").First();



回答2:


What type of brush is this? If its drawing namespace, then brush is an abstract class.! For SolidBrush, do:

brush.Color.ToString()

Otherwise, get the color property and use ToString() method to convert color to its string representation.




回答3:


Basically I'll post what was already answered.

string color = textBox1.Text;

// best, using Color's static method
Color red1 = Color.FromName(color);

// using a ColorConverter
TypeConverter tc1 = TypeDescriptor.GetConverter(typeof(Color)); // ..or..
TypeConverter tc2 = new ColorConverter();
Color red2 = (Color)tc.ConvertFromString(color);

// using Reflection on Color or Brush
Color red3 = (Color)typeof(Color).GetProperty(color).GetValue(null, null);

// in WPF you can use a BrushConverter
SolidColorBrush redBrush = (SolidColorBrush)new BrushConverter().ConvertFromString(color);

Original answer: Convert string to Brushes/Brush color name in C#



来源:https://stackoverflow.com/questions/12842003/c-sharp-brush-to-string

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