Search code examples
iosobjective-ccolorshsvimagefilter

iOS how to calculate hue shift between two UIColors to plug into an image filter?


I want to dynamically recolor images that are in red into any color the user wants (except black and white). This will allow me to reduce the amount of work graphics artist has to do. Typically I do this by applying iOS hue shift filter. This requires entering a number in the 0-1.0 range to specify by how much the hue should be shifted.

Here's how my hue shift control looks currently: enter image description here

I'm trying to make the process simpler by allowing the user to pick the "final" color instead of entering a hue shift number.

For example:

I have a base image in red colors, the user wants this image to be recolored in blue. The user would pick blue, and the code will calculate the hue shift offset from red to blue, and then apply a hue shift filter to the red image, producing the blue one.

-(float)hueShiftFromColor:(UIColor*)originalColor toDesiredColor:(UIColor*)desiredColor;

-OR- if I can use my code to sample a pixel at some point and find it's color, then only the desired color is needed:

-(void)applyHueShiftFilterToBaseImage:(UIImage*)baseImage desiredColor:(UIColor*)desiredColor;

How can I calculate the hue shift difference between two colors (assuming saturation and brightness are kept the same as original color)?


Solution

  • Look at the method

    - (BOOL)getHue:(CGFloat *)hue
        saturation:(CGFloat *)saturation
        brightness:(CGFloat *)brightness
             alpha:(CGFloat *)alpha
    

    So you can do:

    CGFloat hue1;
    CGFloat hue2;
    

    then:

    [color1 getHue:&hue1 saturation:nil brightness:nil alpha:nil];    
    [color2 getHue:&hue2 saturation:nil brightness:nil alpha:nil];
    

    and now you can get the difference between the 2 hue values.

    NSLog(@"hue 1 = %f; hue 2 = %f", hue1, hue2);
    NSLog(@"hue shift = %f", hue1 - hue2);
    

    These are the values I get using redColor and blueColor form UIKit:

    hue 1 = 1.000000; hue 2 = 0.666667
    hue shift = 0.333333
    

    Hope it helps.