|
|
|
Convert the Color structure to HTML and vice versa
8
Have you ever tried to use Color.Blue.ToString and gotten undesired results?
Or have you ever tried to save a color to an INI and not be able to reproduce it the next time around?
The methods below will help you in your conquest of converting the Color structure to HTML (#FF0000) and back to a Color structure again.
Or have you ever tried to save a color to an INI and not be able to reproduce it the next time around?
The methods below will help you in your conquest of converting the Color structure to HTML (#FF0000) and back to a Color structure again.
Public Function Color2Html(ByVal clr As Color) As String
Return "#" & clr.ToArgb().ToString("x").Substring(2)
End Function
Dim myHTML As String = Color2Html(Color.Blue)
'myHTML now contains #0000FF
Public Function HexToColor(ByVal hexString As String) As Color
Try
Dim r, g, b As Integer
hexString = hexString.Replace("#", Nothing)
If Not hexString.Length = 6 Then
Return Color.Black
End If
r = HexToInt(hexString.Substring(0, 2))
g = HexToInt(hexString.Substring(2, 2))
b = HexToInt(hexString.Substring(4, 2))
Return Color.FromArgb(255, r, g, b)
Catch ex As Exception
Debug.WriteLine(ex.ToString)
Return Color.Black
End Try
End Function
'Keep it Global
Private Function HexToInt(ByVal hexString As String) As Int32
Return Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber, Nothing)
End Function
Dim myColor As Color = HexToColor("#0000FF")
'myColor is now Color.Blue
Enjoy,
-Pio




Dim cc As System.Drawing.ColorConverter = New System.Drawing.ColorConverter
Me.BackColor = cc.ConvertFromString("#3FF134")
Dim myConverter As ColorConverter = New ColorConverter
Dim myColor As Color = DirectCast(myConverter.ConvertFromString("#017CCF"), Color)
This works as stated.
About using CInt though:
1. CInt is a legacy function. You should use Convert.ToInt32 instead.
2. Using Globalization is used to keep your application working in different language environments.
Thanks for your comment.
Allen / Pio
email: intolerance@gmail.com