vb.net 在 .NET 中将字符串转换为 System.Color
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21650261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert a String to a System.Color in .NET
提问by user2895707
Good day, I'm trying to make this application on VB.NET in which the user can change the background color of the application, when the application closes the color should save to a XML. The saving was piece of cake but now the real dilemma is how to convert the String "Color[white]"to a System.Color.
美好的一天,我正在尝试在 VB.NET 上制作此应用程序,其中用户可以更改应用程序的背景颜色,当应用程序关闭时,颜色应保存到 XML。节省是小菜一碟,但现在真正的困境是如何将 String 转换"Color[white]"为System.Color.
I already Googled my problem but no result. Plus I'm already familiar to Color.FromName.
我已经用谷歌搜索了我的问题,但没有结果。另外我已经很熟悉了Color.FromName。
Thanks in advanced.
提前致谢。
采纳答案by dotNET
Dim C = System.Drawing.Color.FromName(YourColorString.Replace("Color[" , "").Replace("]", ""))
回答by Manny
Are you familiar with Color.FromName? That should do it.
你熟悉Color.FromName吗?那应该这样做。
http://msdn.microsoft.com/en-us/library/system.drawing.color.fromname(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/system.drawing.color.fromname(v=vs.110).aspx
Dim slateBlue As Color = Color.FromName("SlateBlue")
Dim slateBlue As Color = Color.FromName("SlateBlue")
@dotNet's answer has an example on how to parse out just the name. If you can optionally have a color value stored as red, green, blue, and alpha values, then there is also Color.FromArgb.
@dotNet 的回答有一个关于如何仅解析名称的示例。如果您可以选择将颜色值存储为红色、绿色、蓝色和 alpha 值,那么还有Color.FromArgb.
http://msdn.microsoft.com/en-us/library/at1k42eh(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/at1k42eh(v=vs.110).aspx
Dim red As Color = Color.FromArgb(alpha, 255, 0, 0)
Dim red As Color = Color.FromArgb(alpha, 255, 0, 0)
Edit...@Plutonix also has an interesting suggestion.
编辑...@Plutonix 也有一个有趣的建议。
回答by Andrew Morton
If you save a colour which isn't one of the named colours, it writes it in the format Color [A=99, R=99, G=19, B=255]. You can parse your string for that too:
如果您保存的颜色不是命名颜色之一,它会将其写入格式Color [A=99, R=99, G=19, B=255]. 您也可以为此解析您的字符串:
Option Infer On
Imports System.Text.RegularExpressions
' ...
''' <summary>
''' Convert a string of the format "color [nameOfColor]" or
''' "color [A=a, R=r, G=g, B=b]" to a System.Drawing.Color.
''' </summary>
''' <param name="s">A String representing the colour.</param>
''' <returns>A System.Drawing.Color.</returns>
''' <remarks>Returns fallbackColour if the colour could not be parsed.</remarks>
Public Shared Function ColourFromData(s As String) As Color
Dim fallbackColour = Color.Black
If Not s.StartsWith("color", StringComparison.OrdinalIgnoreCase) Then
Return fallbackColour
End If
' Extract whatever is between the brackets.
Dim re = New Regex("\[(.+?)]")
Dim colorNameMatch = re.Match(s)
If Not colorNameMatch.Success Then
Return fallbackColour
End If
Dim colourName = colorNameMatch.Groups(1).Value
' Get the names of the known colours.
'TODO: If this function is called frequently, consider creating allColours as a variable with a larger scope.
Dim allColours = [Enum].GetNames(GetType(System.Drawing.KnownColor))
' Attempt a case-insensitive match to the known colours.
Dim nameOfColour = allColours.FirstOrDefault(Function(c) String.Compare(c, colourName, StringComparison.OrdinalIgnoreCase) = 0)
If Not String.IsNullOrEmpty(nameOfColour) Then
Return Color.FromName(nameOfColour)
End If
' Was not a named colour. Parse for ARGB values.
re = New Regex("A=(\d+).*?R=(\d+).*?G=(\d+).*?B=(\d+)", RegexOptions.IgnoreCase)
Dim componentMatches = re.Match(colourName)
If componentMatches.Success Then
Dim a = Integer.Parse(componentMatches.Groups(1).Value)
Dim r = Integer.Parse(componentMatches.Groups(2).Value)
Dim g = Integer.Parse(componentMatches.Groups(3).Value)
Dim b = Integer.Parse(componentMatches.Groups(4).Value)
Dim maxValue = 255
If a > maxValue OrElse r > maxValue OrElse g > maxValue OrElse b > maxValue Then
Return fallbackColour
End If
Return System.Drawing.Color.FromArgb(a, r, g, b)
End If
Return fallbackColour
End Function
You could throw a FormatException instead of returning a fall-back value if you wanted to.
如果您愿意,您可以抛出 FormatException 而不是返回回退值。
回答by Tim F.
Just for future "searchers" There is a color.Toargb and color.Fromargb which converts into, and out, of an integer which is serializable.
仅供未来的“搜索者”使用 color.Toargb 和 color.Fromargb 可以将可序列化的整数转换为和输出。
回答by ??ssa P?ngj?rdenlarp
Especially when serializing, it is often worthwhile to make the process agnostic - it ought not care whether it is an ARGB string or named color. And for that matter, it can be made to not care whether it is a Font, Point, Size, Color or Rectangle. Just use the Converter procedures built into .NET. (Note: your color name looks irregular, this depends on NET handling the To and From):
特别是在序列化时,通常值得让过程不可知——它不应该关心它是 ARGB 字符串还是命名颜色。就此而言,可以不关心它是字体、点、大小、颜色还是矩形。只需使用 .NET 中内置的转换器程序即可。(注意:您的颜色名称看起来不规则,这取决于 NET 处理 To 和 From):
_text = TypeDescriptor.GetConverter(v.GetType).ConvertToInvariantString(v)
This will give you a string that can be converted back to a font, point, rectangle etc, depending on what type vis. To get back the object:
这将为您提供一个字符串,该字符串可以转换回字体、点、矩形等,具体取决于类型v。取回对象:
myColor = TypeDescriptor.GetConverter(GetType(System.Drawing.Color)) _
.ConvertFromInvariantString(_text)
If you wrap it in a function using a generic, it can be able to unpack agnostically as well:
如果您使用泛型将它包装在一个函数中,它也可以不可知地解包:
Function ConvertMyThing(Of T)(text as String) As T
return CType(TypeDescriptor.GetConverter(GetType(T)) _
.ConvertFromInvariantString(text), T)
End Function
Usage:
用法:
myColor = ConvertMyThing(Of Color)(colorString)
ConvertToInvariantStringis notthe same as ToString. ToStringmakes debug/human friendly text like Color [A=99, R=99, G=19, B=255]or similar for Point, Size etc. The color output from ConvertToInvariantStringwould simply be 99, 19, 255(it apparently omits Aif it is 255).
ConvertToInvariantString是不一样的ToString。 为 Point、Size 等制作ToString类似Color [A=99, R=99, G=19, B=255]或类似的调试/人类友好文本。来自的颜色输出ConvertToInvariantString将只是99, 19, 255(A如果它是 255,它显然会省略)。
For Color, it is great because there is no parsing required, no RegEx, no Splitting, Joining, no fuss and no muss. As a bonus it will handle Point, Font, Rectangle, Size, Decimal... System.Enum is more trouble than Font.
对于 Color,它很棒,因为不需要解析,不需要正则表达式,不需要拆分、连接,没有大惊小怪。作为奖励,它将处理点、字体、矩形、大小、十进制...... System.Enum 比字体更麻烦。
回答by Dom Sinclair
If this is winforms why don't you use My.settings (click on my project in the solution explorer, click on the settings tab,create a new setting of type system.drawing.color with scope set to user). You can assign the background colour of a form or forms to use the relevant setting (in the properties for the form open up application settings, click on property bindings and in the dialog that pops up assign BackColour to the setting you created).
如果这是 winforms 为什么不使用 My.settings(在解决方案资源管理器中单击我的项目,单击设置选项卡,创建一个 system.drawing.color 类型的新设置,范围设置为用户)。您可以分配一个或多个表单的背景颜色以使用相关设置(在表单的属性中打开应用程序设置,单击属性绑定并在弹出的对话框中将 BackColour 分配给您创建的设置)。
Make sure on application close you save the settings (My.Settings.save). Whatever the end user selects as a colour will be saved between sessions.
确保在应用程序关闭时保存设置 (My.Settings.save)。最终用户选择的颜色将在会话之间保存。
回答by M.M.Rame
It may be an old question, but, an answer is always useful: When extracting the color, pick it up as RGB (it's easier to convert it back). For example, you could use : Dim S AS String = ctrl.BackColor.ToArgb.ToString
这可能是一个老问题,但是,一个答案总是有用的:提取颜色时,将其提取为 RGB(将其转换回更容易)。例如,您可以使用: Dim S AS String = ctrl.BackColor.ToArgb.ToString
to get it back, you should use: ctrl.BackColor = Color.FromArgb(CInt(S)) In this case, You don't have to just serialize it : The property can be extracted to a text, a memoryFile, used in XML Or any other Cases (when you need to put this setting in a "delimeterd" line, and parsing it later to get this color back) Nevertheless, this BackColor as described in your question is more like a setting, so, consider using My.Settings and save it before closing as described in the answer of Dom Sinclair (above), this could be a better approach
要取回它,你应该使用: ctrl.BackColor = Color.FromArgb(CInt(S)) 在这种情况下,你不必只是序列化它:该属性可以被提取到一个文本,一个内存文件,用于XML 或任何其他案例(当您需要将此设置放在“分隔”行中,并稍后对其进行解析以恢复此颜色时)不过,您问题中描述的此 BackColor 更像是一个设置,因此,请考虑使用 My .设置并在关闭之前保存它,如 Dom Sinclair(上面)的回答中所述,这可能是更好的方法

