2012-04-27 31 views
4

UITabBar默認繪製一個微妙的梯度:繪製漸變像UITabBar與tintColor

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

回答