Hi all! Is there a (out of the box) way to obtain ...
# compose
a
Hi all! Is there a (out of the box) way to obtain the Hex value (as #aaxxyyzz) from a given
Color
?
k
Color.toArgb
will give you an "encoded" integer, and then you can do
"#%08X".format(argbInt)
on it
Note that
String.format
is not in common, but rather only available for jvm at the moment - https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/format.html
e
in this case you could do something like
Copy code
"#" + argbInt.toUInt().toString(radix = 16).padStart(8, '0')
in common, although ideally we'd have a common function for this https://youtrack.jetbrains.com/issue/KT-50309
a
hey, the first optioon worked perfect1
Just.. is ther a way to obtain it withut alpha?
c
heres some code iw rote to do this
Copy code
val textColor =
    Integer.toHexString(colorValue.toArgb())
        .padStart(8, '0')
        .toUpperCase(Locale.ROOT)
        .removeRange(0, 2)
val transparencyValue =
    if (shouldShowTransparencyValue)
        Integer.toHexString(colorValue.toArgb())
            .padStart(8, '0')
            .toUpperCase(Locale.ROOT)
            .take(2)
            .getTransparencyValue()
    else ""
Copy code
/** Helper to get a human readable alpha percentage from a 2 char hex code */
private fun String.getTransparencyValue(): String {
  return (this.toInt(16) / 255F * 100).roundToInt().toString() + "%"
}
e
Integer is JVM-only. if you need common, you can do something like
Copy code
argbInt.and(0xffffff).toString(radix = 16).padStart(6, '0')
to mask off the alpha
mind blown 1
a
I think you can just use
"#%06X".format(color.toArgb() and 0xFFFFFF)
.
mind blown 1
c
@alorma let me know what you end up using. This code in my codebase looks super hacky and so if you write some ext function that you wanna share here, that works for me. 😄
a
I've end up using @Albert Chang version... but feeling like
☝️ 1
☝🏽 1
c
@alorma you should file a bug/FR for provide an extension from color to string hex value. I'd star it. Worth a shot. 😅
e
the
.format()
functions are all JVM-only, I was providing non-JVM variants since that was brought up by Kirill
I agree that (regardless of non-JVM-specific formatting) colors should have both parsing and stringification in Compose
K 1
k
It gets tricky. Or maybe not tricky, but there's an implicit assumption in here that sRGB color space is the one and only way to "represent" a color. So yes, it is a rather traditional default way of specifying color, but it's just one of more than a dozen color spaces supported by Compose.
e
that's fair, but Color(Int) and Color.toArgb() are sRGB so it is special