在代码中使用tintColor绘制UITabBar等渐变

时间:2012-04-27 22:00:43

标签: ios colors drawing gradient drawrect

UITabBar默认情况下绘制一个微妙的渐变:

UITabBar Gradient Black

我想用任何给定的tintColor在我的代码中复制这个外观。为了说清楚:我不想在UITabBar上设置tintColor(这可以从iOS 5开始),我想在我自己的UIView中绘制渐变。

我知道如何绘制渐变,我的问题是如何从tintColor派生渐变的颜色。我正在考虑获得颜色的亮度,并使用不同的亮度设置生成其他颜色,但这似乎不能很好地工作,看起来不像我想要的那样好。

Custom Drawn Gradient

我需要开源TabBarController的代码:https://github.com/NOUSguide/NGTabBarController

这是我目前创建渐变的代码:

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);
}

1 个答案:

答案 0 :(得分:5)