Is there a provided way that we have to interpret ...
# compose-desktop
s
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
What does interpret mean?
t
Your function would fail for colours with an alpha value. Try parsing #FFFFFFFF. Probably you should use Long.
s
@Kirill Grouchnikov interpret = parse
@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
Your code still uses toInt so it crashes with #FFFFFFFF
s
yeah - I have it working with Long. I was playing around in my head with whether or not UInt would work
UInt appears to work. Fun fact,
UInt.MAX_VALUE == 0xFFFFFFFFu
First time I’ve ever found a use for UInt in my code 😛