Title
a

alorma

01/11/2022, 4:47 PM
Hi all! Is there a (out of the box) way to obtain the Hex value (as #aaxxyyzz) from a given
``Color``
?
k

Kirill Grouchnikov

01/11/2022, 4:54 PM
``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

ephemient

01/11/2022, 5:20 PM
in this case you could do something like
``"#" + 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

alorma

01/11/2022, 5:26 PM
hey, the first optioon worked perfect1
Just.. is ther a way to obtain it withut alpha?
c

Colton Idle

01/11/2022, 5:26 PM
heres some code iw rote to do this
``````val textColor =
Integer.toHexString(colorValue.toArgb())
.toUpperCase(Locale.ROOT)
.removeRange(0, 2)
val transparencyValue =
if (shouldShowTransparencyValue)
Integer.toHexString(colorValue.toArgb())
.toUpperCase(Locale.ROOT)
.take(2)
.getTransparencyValue()
else ""``````
``````/** 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

ephemient

01/11/2022, 5:41 PM
Integer is JVM-only. if you need common, you can do something like
``argbInt.and(0xffffff).toString(radix = 16).padStart(6, '0')``
:mind-blown: 1
a

Albert Chang

01/11/2022, 5:51 PM
I think you can just use
``"#%06X".format(color.toArgb() and 0xFFFFFF)``
.
:mind-blown: 1
c

Colton Idle

01/11/2022, 5:52 PM
@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

alorma

01/11/2022, 6:04 PM
I've end up using @Albert Chang version... but feeling like
āļø 1
āļøš½ 1
c

Colton Idle

01/11/2022, 6:11 PM
@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

ephemient

01/11/2022, 6:20 PM
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
:kotlin-intensifies: 1
k

Kirill Grouchnikov

01/11/2022, 6:29 PM
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

ephemient

01/11/2022, 6:46 PM
that's fair, but Color(Int) and Color.toArgb() are sRGB so it is special