fuzz fuzz - 3 months ago 17
Swift Question

Getting hue from UIColor yields wrong result

I'm doing the following in order to retrieve the

hue
from a
UIColor()
:

let rgbColour = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)
var hue: CGFloat = 0
var saturation: CGFloat = 0
var brightness: CGFloat = 0
var alpha: CGFloat = 0
rgbColour.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)

println("\(hue),\(saturation),\(brightness)")


Output:

1.0,1.0,1.0


According to this link, I'm meant to be getting
0.0,1.0,1.0
for RGB (red)
1.0,0.0,0.0
.

Am I doing something wrong?

Answer

First of all the range of the red/green/blue components in UIColor is 0.0 .. 1.0, not 0.0 .. 255.0, so you probably want

let rgbColour = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)

But even then you get the output 1.0,1.0,1.0 and this is correct. The hue component ranges from 0.0 to 1.0, which corresponds to the angle from 0º to 360º in a color wheel (see for example HSL and HSV).

Therefore hue = 0.0 and hue = 1.0 describe an identical color. If you need to normalize the hue component to the half-open interval 0.0 <= hue < 1.0 then you could do that with

hue = fmod(hue, 1.0)
Comments