ARTICLE
How to write and read a Color in VB.NET
This article shows how to transform a color in hexadecimal representation.
Download
Files:
Transforming a color in hexa representation using following function:
Private
Function WriteHexString(ByVal aobjColR As Byte, ByVal aobjColG As Byte, ByVal aobjColB As Byte) As String
Dim strRet As String
Dim btR As Byte() = {aobjColR}
Dim strR As String = ToHexString(btR)
strRet = strR
Dim btG As Byte() = {Me.colorDialog1.Color.G}
Dim strG As String = ToHexString(btG)
strRet &= strG
Dim btB As Byte() = {Me.colorDialog1.Color.B}
Dim strB As String = ToHexString(btB)
strRet &= strB
Return strRet
End Function 'WriteHexString This function transform a Color (defined as Color.R, Color.G, Color.B) in hexa representation (as string) and use following helper functions:
Private
Shared Function ToHexString(ByVal bytes As Byte()) As String
Dim chars As Char() = New Char(bytes.Length * 2 - 1) {}
Dim i As Integer = 0
Do While i < bytes.Length
Dim b As Integer = bytes(i)
chars(i * 2) = hexDigits(b >> 4)
chars(i * 2 + 1) = hexDigits(b And &HF)
i += 1
Loop
Return New String(chars)
End Function 'ToHexString Shared
hexDigits() As Char = {"0"c, "1"c, "2"c, "3"c, "4"c, "5"c, "6"c, "7"c, "8"c, "9"c, "A"c, "B"c, "C"c, "D"c, "E"c, "F"c} To transform "hexa" representation back in color we can use following function:
Private
Function GetColor(ByVal astrHexString As String) As Color
Dim strR As String
Dim strG As String
Dim strB As String
Dim strRL As String
Dim strRR As String
Dim strGL As String
Dim strGR As String
Dim strBL As String
Dim strBR As String
Dim iR As Integer
Dim iG As Integer
Dim iB As Integer
Dim iRL As Integer
Dim iRR As Integer
Dim iGL As Integer
Dim iGR As Integer
Dim iBL As Integer
Dim iBR As Integer
Dim c As Color strR = astrHexString.Substring(0, 2)
strG = astrHexString.Substring(2, 2)
strB = astrHexString.Substring(4, 2)
strRL = strR.Substring(0, 1)
strRR = strR.Substring(1, 1)
strGL = strG.Substring(0, 1)
strGR = strG.Substring(1, 1)
strBL = strB.Substring(0, 1)
strBR = strB.Substring(1, 1)
iRL = GetIntFromHex(strRL)
iRR = GetIntFromHex(strRR)
iGL = GetIntFromHex(strGL)
iGR = GetIntFromHex(strGR)
iBL = GetIntFromHex(strBL)
iBR = GetIntFromHex(strBR)
iR = 16 * iRL + iRR
iG = 16 * iGL + iGR
iB = 16 * iBL + iBR
c = Color.FromArgb(iR, iG, iB)
Return c End Function 'GetColour The complete code is in zip file. NOTE: THIS ARTICLE IS CONVERTED FROM C# TO VB.NET USING A CONVERSION TOOL. ORIGINAL ARTICLE CAN BE FOUND ON C# CORNER (WWW.C-SHARPCORNER.COM).