Draw gradient like UITabBar with tintColor in code

colors, drawing, drawrect, gradient, ios

Solution

Here is an excellent tutorial: http://www.raywenderlich.com/2079/core-graphics-101-shadows-and-gloss look at the part with the gloss effect.

Also here: http://cocoawithlove.com/2008/09/drawing-gloss-gradients-in-coregraphics.html

And a complete code sample here: http://www.mlsite.net/blog/?page_id=372

Problem

UITabBar by default draws a subtle gradient: I would like to replicate this look and feel in my code with any given tintColor. Just to make it clear: I do not want to set a tintColor on UITabBar (which is possible since iOS 5), I would like to draw the gradient in my own UIView. I know how to draw the gradient, my problem is how to derive the colors for the gradient from the tintColor. I was thinking about getting the brightness of the color and generating the other colors with different brightness-settings, but that doesn't seem to work that well and looks not as good as I would like it to look. I need the code for my open source TabBarController: https://github.com/NOUSguide/NGTabBarController Here's my current code for creating the gradient: ``` UIColor *baseColor = self.tintColor; CGFloat hue, saturation, brightness, alpha; // TODO: Only works on iOS 5 [baseColor getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha]; // That's the question, how to compute the colors ... NSArray *colors = [NSArray arrayWithObjects: [UIColor colorWithHue:hue saturation:saturation brightness:brightness+0.2 alpha:alpha], [UIColor colorWithHue:hue saturation:saturation brightness:brightness+0.15 alpha:alpha], [UIColor colorWithHue:hue saturation:saturation brightness:brightness+0.1 alpha:alpha], baseColor, nil]; NSUInteger colorsCount = colors.count; CGColorSpaceRef colorSpace = CGColorGetColorSpace([[colors objectAtIndex:0] CGColor]); NSArray *locations = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0], [NSNumber numberWithFloat:0.25], [NSNumber numberWithFloat:0.49], [NSNumber numberWithFloat:0.5], nil]; CGFloat *gradientLocations = NULL; NSUInteger locationsCount = locations.count; gradientLocations = (CGFloat *)malloc(sizeof(CGFloat) * locationsCount); for (NSUInteger i = 0; i < locationsCount; i++) { gradientLocations[i] = [[locations objectAtIndex:i] floatValue]; } NSMutableArray *gradientColors = [[NSMutableArray alloc] initWithCapacity:colorsCount]; [colors enumerateObjectsUsingBlock:^(id object, NSUInteger index, BOOL *stop) { [gradientColors addObject:(id)[(UIColor *)object CGColor]]; }]; _gradientRef = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)gradientColors, gradientLocations); if (gradientLocations) { free(gradientLocations); } ```

Original source