iosobjective-cgradientappkitnsgradient

Interpolating gradient colors (as with NSGradient) on iOS?


AppKit is not available in iOS, so I was looking for a replacement.

Specifically, I was looking for a replacement method for:

- (NSColor *)interpolatedColorAtLocation: (CGFloat)location

I need a way to define a gradient, and lookup a colour value based on an input location (float).


Solution

  • If you actually need a gradient object (for drawing the gradient?), you can use the CG-level CGGradient "class".

    As for interpolating the color at a specific location in the gradient all you need to know are the two surrounding colors (relative to your given location) and the interpolate between them (t would then be a location between 0.0..1.0 relative to the two colors, not the entire gradient):

    - (UIColor *)colorByInterpolatingWith:(UIColor *)color factor:(CGFloat)factor {
        factor = MIN(MAX(t, 0.0), 1.0);
    
        const CGFloat *startComponent = CGColorGetComponents(self.CGColor);
        const CGFloat *endComponent = CGColorGetComponents(color.CGColor);
    
        float startAlpha = CGColorGetAlpha(self.CGColor);
        float endAlpha = CGColorGetAlpha(color.CGColor);
    
        float r = startComponent[0] + (endComponent[0] - startComponent[0]) * factor;
        float g = startComponent[1] + (endComponent[1] - startComponent[1]) * factor;
        float b = startComponent[2] + (endComponent[2] - startComponent[2]) * factor;
        float a = startAlpha + (endAlpha - startAlpha) * factor;
    
        return [UIColor colorWithRed:r green:g blue:b alpha:a];
    }
    

    Example use:

    UIColor *purpleColor = [[UIColor redColor] colorByInterpolatingWith:[UIColor blueColor] factor:0.5];