Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting hue from UIColor yields wrong result

Tags:

swift

rgb

uicolor

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?

like image 428
fulvio Avatar asked Feb 17 '15 15:02

fulvio


2 Answers

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)
like image 187
Martin R Avatar answered Nov 20 '22 17:11

Martin R


To build on @Martin R's answer:

If you wanted to use HSB, you need to:

  1. Divide the hue value by 360
  2. Use decimals for the Saturation and Brightness values

So, say for example that Sketch is telling you the colour values in HSB are: Hue: 20, Saturation: 72 and Brightness: 96

In Xcode, create the colour as follows:

let myAwesomeColour = UIColor(hue: 20/360, saturation: 0.72, brightness: 0.96, alpha: 1.0)

Whether you use RGB or HSB is a matter of preference. The results are the same as far as Xcode is concerned, they both translate to a UIColor.

like image 23
kakubei Avatar answered Nov 20 '22 19:11

kakubei