Search code examples
iosswiftcolorsuicolor

How to "rotate" the hue of a color?


I want to generate colors that go well with a given UIColor (Triadic, Analogues, Complement etc).

I have read a lot of posts like this and this and this. In the last post, The answerer suggested going to easyrgb.com. So I went there. I learnt that I need to "rotate" the hue by some degrees if I want to generate those color schemes. For example, for Triadic colors, I need to rotate it by ± 120 degrees.

I know that I can get a color's hue by calling getHue(:saturation:brightness:), but how can I "rotate" it? Isn't the hue returned by the method a number? A number between 0 and 1? This makes no sense to me!

I think the first post might have the answer but the code is written in python. I only learnt a little bit of python so I don't quite know what this means:

h = [(h+d) % 1 for d in (-d, d)]           # Rotation by d

From the comment, I see that this line somehow rotates the hue by d degrees. But I don't know what that syntax means.

Can anyone tell me how to rotate the hue, or translate the above code to swift?


Solution

  • The hue component ranges from 0.0 to 1.0, which corresponds to the angle from 0º to 360º in a color wheel (compare Wikipedia: HSL and HSV).

    To "rotate" the hue component by n degrees, use:

    let n = 120 // 120 degrees as an example
    hue = fmod(hue + CGFloat(n)/360.0, 1.0)
    

    The fmod() function is used to normalize the result of the addition to the range 0.0 to 1.0.

    The hue for the complementary color would be

    let hueComplement = fmod(hue + 0.5, 1.0)