hex (text) value to color

Is there a way to convert a hex value to color in iOS?

in a desktop app I can do something like this:

dim c as color
dim t as text = "&cFF0000"
c = color(ctype(val(t), integer))

But in iOS the val function is not supported :confused:

[code] dim t as text = “&hFF800100” // The hex value
dim red, green, blue, alpha as integer
red = Integer.FromHex(t.mid(2,2))
green = Integer.FromHex(t.mid(4,2))
blue = Integer.FromHex(t.mid(6,2))
alpha = Integer.FromHex(t.mid(8,2))

dim c as color = Color.RGBA(red, green, blue, alpha)[/code]

[quote=220587:@Michel Bujardet][code] dim t as text = “&hFF800100” // The hex value
dim red, green, blue, alpha as integer
red = Integer.FromHex(t.mid(2,2))
green = Integer.FromHex(t.mid(4,2))
blue = Integer.FromHex(t.mid(6,2))
alpha = Integer.FromHex(t.mid(8,2))

dim c as color = Color.RGBA(red, green, blue, alpha)[/code][/quote]

I just figured it out just now, about 7 minutes ago. I was fiddling with the Integer shared methods. And I was just now posting an answer to my own post.

But thanks anyway Michel :slight_smile:

I think I found a shorter way:

dim t as text = "00FF00"
dim i as integer = Integer.FromHex( t )
dim c as color = color( i )

I tested this. It resulted in a green color, as expected!

Alpha is not supported this way though. I tried casting via Uinteger, and Uint64, and a bunch of other integer types.
So, I think a solution is to see if t.length = 8. Take the t.right(2) value, and use that as the alpha value

Should’t it be?

[code] dim t as text = “&hFF800100” // The hex value
dim red, green, blue, alpha as integer
red = Integer.FromHex(t.mid(3,2))
green = Integer.FromHex(t.mid(5,2))
blue = Integer.FromHex(t.mid(7,2))
alpha = Integer.FromHex(t.mid(9,2))

dim c as color = Color.RGBA(red, green, blue, alpha)[/code]

[quote=220731:@David Cox]Should’t it be?

[code] dim t as text = “&hFF800100” // The hex value
dim red, green, blue, alpha as integer
red = Integer.FromHex(t.mid(3,2))
green = Integer.FromHex(t.mid(5,2))
blue = Integer.FromHex(t.mid(7,2))
alpha = Integer.FromHex(t.mid(9,2))

dim c as color = Color.RGBA(red, green, blue, alpha)[/code][/quote]

In a way you are right, David. But, something I didn’t write in my examples was the stripping of any characters like &h, &c or # at the beginning of the hex value. Sorry about that.
Integer.FromHex can deal with values that only contain the Hex letters. The literal prefix is not needed, and actually not used in this particular code (omitted in your example by the t.mid(3,2) ) . So, I am not going to store that in my JSON or SQL data.
Therefore I pull the Hex bytes starting at index 1, not 3.

But er… thanks for noting that :slight_smile:
(Someone has his coffee today :wink: )

'convert integer i into color c
dim i as integer
dim v as variant
dim c as color
v=i
c=v.colorvalue

…works for me. I used to use the color() function but xojo 2015 v3.1 didn’t like it. So we trick it with a variant.