Android Question Hex color for HTML output

Andrew Gray

Member
Licensed User
Longtime User
Hi everyone,

Does anyone have code for turning a Color in B4A (an integer) into a hex string like those used in HTML?

E.g. blue would be #0000ff.

Bit.ToHexString doesn't achieve the desired result.

Thanks!

Andrew
 

RandomCoder

Well-Known Member
Licensed User
Longtime User
From my ColorPicker class which I've never actually got round to posting. If you want the Alpha to be settable it will need that adding but should be self explanatory. Hopefully you can tailor this to your needs....
B4X:
Private Sub getARGBColor(intColor As Int) As Int() ' Courtesy of B4A administrator Erel
    ' Extract each component part of the colour integer value
    Dim intColors(4) As Int
    intColors(0) = Bit.UnsignedShiftRight(Bit.And(intColor, 0xff000000), 24)
    intColors(1) = Bit.UnsignedShiftRight(Bit.And(intColor, 0xff0000), 16)
    intColors(2) = Bit.UnsignedShiftRight(Bit.And(intColor, 0xff00), 8)
    intColors(3) = Bit.And(intColor, 0xff)
    Return intColors

'Get or set hex color value of currently selected pallet
Public Sub getSelectedColorHex() As String
    Dim strHex As String
    strHex = Bit.ToHexString(intARGB(0))
    strHex = strHex & Bit.ToHexString(intARGB(1))
    strHex = strHex & Bit.ToHexString(intARGB(2))
    strHex = strHex & Bit.ToHexString(intARGB(3))
    Return strHex
End Sub

Public Sub setSelectedColorHex(HexColor As String)
    If HexColor.Length = 10 Or HexColor.Length = 8  Then
        If HexColor.Length = 10 Then HexColor = HexColor.SubString(2)
        intARGB(0) = 255 ' Alpha not supported in this version, forced to fully opaque (255)
        intARGB(1) = Bit.ParseInt(HexColor.SubString2(2,4), 16)
        intARGB(2) = Bit.ParseInt(HexColor.SubString2(4,6), 16)
        intARGB(3) = Bit.ParseInt(HexColor.SubString2(6,8), 16)
        setActivePalletColor(Colors.ARGB(intARGB(0), intARGB(1), intARGB(2), intARGB(3)))
    End If
End Sub
 
Upvote 0

Andrew Gray

Member
Licensed User
Longtime User
Thanks!

The following also seems to work, I just needed to get rid of the Alpha byte:

B4X:
hexcolor = "#" & Bit.ToHexString(Bit.And(0xFFFFFF, intcolor))
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…