Is there a provided way that we have to interpret a hex string color, or is the best way to do something like
Copy code
colorString.removePrefix("#").toInt(16)
k
Kirill Grouchnikov
05/09/2022, 9:12 PM
What does interpret mean?
t
Thomas
05/09/2022, 9:59 PM
Your function would fail for colours with an alpha value. Try parsing #FFFFFFFF. Probably you should use Long.
s
spierce7
05/10/2022, 1:34 AM
@Kirill Grouchnikov interpret = parse
spierce7
05/10/2022, 1:40 AM
@Thomas I ended up running into both of those issues. Thanks. Especially since
Color
assumes ARGB.
I ended up just making the following function:
Copy code
fun String.hexStringToColor(): Color {
val colorString = removePrefix("#")
val argb = colorString.toUInt(16)
val b: Int = (argb and 0xFFu).toInt()
val g: Int = (argb shr 8 and 0xFFu).toInt()
val r: Int = (argb shr 16 and 0xFFu).toInt()
val a: Int = (argb shr 24 and 0xFFu).toInt()
return when (colorString.length) {
6 -> Color(red = r, green = g, blue = b)
8 -> Color(red = r, green = g, blue = b, alpha = a)
else -> throw IllegalArgumentException("Unexpected hex color value in String: '$this'")
}
}
👍🏻 1
t
Thomas
05/10/2022, 1:45 AM
Your code still uses toInt so it crashes with #FFFFFFFF
s
spierce7
05/10/2022, 1:46 AM
yeah - I have it working with Long. I was playing around in my head with whether or not UInt would work
spierce7
05/10/2022, 1:55 AM
UInt appears to work. Fun fact,
UInt.MAX_VALUE == 0xFFFFFFFFu
First time I’ve ever found a use for UInt in my code 😛