Search code examples
iosswiftuicolor

Wrong results for the HSV conversion?


I have this code to convert from RGB to HSV

  func rgbToHSV (_ r:Double, _ g:Double, _ b:Double) -> (Double, Double, Double) {

    let cor01 : (Double) -> CGFloat = { valor in
      return CGFloat(valor / 255)
    }

    let corRGB = UIColor(red: cor01(r),
                         green: cor01(g),
                         blue: cor01(b),
                         alpha: 1.0)

    var hue         : CGFloat = CGFloat.infinity
    var saturation  : CGFloat = CGFloat.infinity
    var brightness  : CGFloat = CGFloat.infinity
    var alpha       : CGFloat = CGFloat.infinity

    _ = corRGB.getHue(&hue,
                      saturation:&saturation,
                      brightness:&brightness,
                      alpha:&alpha)

    return (Double(hue), Double(saturation), Double(brightness))
  }

I convert RGB = (168, 131, 126) to HSV and get

HUE = 0.019841269841269771
SAT = 0.24999999999999994
BRI = 0.6588235294117647

I use the online conversion of this site and this site and both give me a hue of 7 degrees.

What is going on?


Solution

  • The reason for this is that the value of 0.01984126984126977 comes as a part of a whole, where the whole is 360 degrees. You can multiply by 360 and get a value of 7.1428571428571175.

    let result = rgbToHSV(168, 131, 126)
    print(result)
    print(result.0 * 360)
    

    Output:

    (0.01984126984126977, 0.24999999999999994, 0.6588235294117647)
    7.1428571428571175