Android Question Hex to RGB color?

WAZUMBi

Well-Known Member
Licensed User
Longtime User
From a post by Erel I got sometime ago:

B4X:
Sub getARGB(Color As Int) As Int() 
    Dim res(4) As Int 
    res(0) = Bit.UnsignedShiftRight(Bit.AND(Color, 0xff000000), 24)
    res(1) = Bit.UnsignedShiftRight(Bit.AND(Color, 0xff0000), 16) 
    res(2) = Bit.UnsignedShiftRight(Bit.AND(Color, 0xff00), 8) 
    res(3) = Bit.AND(Color, 0xff)             
    Return res
End Sub
 
Upvote 0

canalrun

Well-Known Member
Licensed User
Longtime User
Hello,
I'm going to change the question a little bit to make the answer a little clearer.

Can I get the RGB values from a number such as #E3E2E1?

This is a notation used describe three 8-bit (each 0 – 255) values each represented by two hexadecimal digits. First two hex digits represent the Red, the second two Green, and the final two Blue.

The three colors in this example are:
Red – E3 (227 decimal)
Green – E2 (226)
Blue – E1 (225)

So you can write statement:
n = Colors.RGB(227, 226, 225)

The post by WAZUMBi is correct. It will take an integer and extract the individual red, green, and blue integer values from the combined color value.

If I take the number (written in hexadecimal notation) #E3E2E1 and convert this to decimal notation I get 14934753. If I feed this number into WAZUMBi's code I will end up with 227, 226, 225 for res(1), res(2), and res(3).

Sorry if I misunderstood the question.
Barry.
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
Maybe this?

B4X:
Sub GetColor(hex As String) As Double
    Dim bc As ByteConverter
    Dim r,g,b As Int
    ' #E3E2E1
    'Log(hex.SubString2(1,3))
    r = Bit.ParseInt(hex.SubString2(1,3), 16)
    g = Bit.ParseInt(hex.SubString2(3,5), 16)
    b = Bit.ParseInt(hex.SubString2(5,7), 16)
    Return Colors.RGB(r, g, b)
End Sub
Sub Activity_Create(FirstTime As Boolean)
    Log(GetColor("#E3E2E1"))
    Log(Colors.RGB(227, 226, 225))
 
Upvote 0

bluedude

Well-Known Member
Licensed User
Longtime User
I have a hex string but the described method (Erel) does not work. The getcolor function works however.
 
Upvote 0

oliverm

Member
Licensed User
Longtime User
DonManFred, I'm trying to use that GetColour procedure you posted in this thread, but I'm getting an error on the line "Dim bc As ByteConverter" asking whether I'm missing a library.

Is there a particular library that I need to add for the ByteConverter type?

Olly
 
Upvote 0

peacemaker

Expert
Licensed User
Longtime User
B4X:
Sub Get_IntColor(HexColor As String) As Int
    Dim res As Int
    If HexColor.StartsWith("#") Then
        res = Bit.ParseInt(HexColor.Replace("#", ""), 16)
        res = Bit.Or(res, 0xFF000000)    'alfa
    Else
        res = 0
    End If
    Return res
End Sub
 
Upvote 0
Top