I'm trying to get the hue value from a Color but I...
# compose
z
I'm trying to get the hue value from a Color but I am struggling with the math behind it, the issue is I keep getting slight variability in the hue when the saturation changes, even though the hue should remain constant. This is the function I currently have
Copy code
public val Color.hue: Float
    get() {
        val (r, g, b) = this

        val max = maxOf(r, g, b)
        val min = minOf(r, g, b)
        val delta = max - min

        return when {
            delta == 0f -> 0f
            max == r -> ((g - b) / delta % 6 + 6) % 6
            max == g -> (b - r) / delta + 2
            else -> (r - g) / delta + 4
        } * 60
    }
And the test I have
Copy code
@Test
    fun testHsvSaturationModification() {
        val initialColor = Color.hsv(
            hue = 233f,
            saturation = 0.5f,
            value = 0.8f
        )

        val modifiedColor = Color.hsv(
            hue = initialColor.hue,
            saturation = 0.8f, // increased saturation
            value = initialColor.hsvValue
        )

        assertEquals(initialColor.hue, modifiedColor.hue)
    }
r
Why do you do the + 6 and two mod 6 in the red case?
z
Hm, im still getting imprecise values. I'm starting to think maybe it's just not possible, or feasible without lots of changes to get precise RGB to HSV/HSL. Even if I round the hue, it slowly drifts as the saturation value changes
r
Considering the math and floats involved, I doubt you'll get a perfect round trip no.
z
@romainguy here is a live sample https://zt64.dev/compose-color/ and the code https://github.com/zt64/compose-color in case you or someone else is able to take a look