Preventing a UITabBar from applying a gradient to its icon images

Apple added tab bar customization in iOS 5, and now this kind of stuff is trivial. Prior to this it was a huge hack, and not recommended.

Here's how to do a completely custom tab bar:

// custom icons
UITabBarItem *item = [[UITabBarItem alloc] init];
item.title = @"foo";
// setting custom images prevents the OS from applying a tint color
[item setFinishedSelectedImage:[UIImage imageNamed:@"tab1_active.png"] withFinishedUnselectedImage:[UIImage imageNamed:@"tab1_image_deselected.png"]];
tab1ViewController.tabBarItem = item;

    // tab bar

    // set background image - will be used instead of glossy black
    tabBarController.tabBar.backgroundImage = [UIImage imageNamed:@"tab_bar_bg.png"];
    // optionally set the tint color - setting this ti nil will result in the standard, blue tint color. tint color is ignored when custom icons are set as above.
    tabBarController.tabBar.selectedImageTintColor = nil;
    // remove the highlight around the selected tab - or provide an alternate highlight image. If you don't do this the iOS default is to draw a highlighted box beneath the selected tab icon.
    tabBarController.tabBar.selectionIndicatorImage = [[UIImage alloc] init];

This is surprisingly difficult as the UITabBar doesn't provide access to it's selected/unselected images. It can be achieved with a private API though:

@interface UITabBar (ColorExtensions)
- (void)recolorItemsWithColor:(UIColor *)color shadowColor:(UIColor *)shadowColor shadowOffset:(CGSize)shadowOffset shadowBlur:(CGFloat)shadowBlur;
@end

@interface UITabBarItem (Private)
@property(retain, nonatomic) UIImage *selectedImage;
- (void)_updateView;
@end

@implementation UITabBar (ColorExtensions)
- (void)recolorItemsWithColor:(UIColor *)color shadowColor:(UIColor *)shadowColor shadowOffset:(CGSize)shadowOffset shadowBlur:(CGFloat)shadowBlur
{
    CGColorRef cgColor = [color CGColor];
    CGColorRef cgShadowColor = [shadowColor CGColor];
    for (UITabBarItem *item in [self items])
        if ([item respondsToSelector:@selector(selectedImage)] &&
            [item respondsToSelector:@selector(setSelectedImage:)] &&
            [item respondsToSelector:@selector(_updateView)])
        {
            CGRect contextRect;
            contextRect.origin.x = 0.0f;
            contextRect.origin.y = 0.0f;
            contextRect.size = [[item selectedImage] size];
            // Retrieve source image and begin image context
            UIImage *itemImage = [item image];
            CGSize itemImageSize = [itemImage size];
            CGPoint itemImagePosition; 
            itemImagePosition.x = ceilf((contextRect.size.width - itemImageSize.width) / 2);
            itemImagePosition.y = ceilf((contextRect.size.height - itemImageSize.height) / 2);
            UIGraphicsBeginImageContext(contextRect.size);
            CGContextRef c = UIGraphicsGetCurrentContext();
            // Setup shadow
            CGContextSetShadowWithColor(c, shadowOffset, shadowBlur, cgShadowColor);
            // Setup transparency layer and clip to mask
            CGContextBeginTransparencyLayer(c, NULL);
            CGContextScaleCTM(c, 1.0, -1.0);
            CGContextClipToMask(c, CGRectMake(itemImagePosition.x, -itemImagePosition.y, itemImageSize.width, -itemImageSize.height), [itemImage CGImage]);
            // Fill and end the transparency layer
            CGContextSetFillColorWithColor(c, cgColor);
            contextRect.size.height = -contextRect.size.height;
            CGContextFillRect(c, contextRect);
            CGContextEndTransparencyLayer(c);
            // Set selected image and end context
            [item setSelectedImage:UIGraphicsGetImageFromCurrentImageContext()];
            UIGraphicsEndImageContext();
            // Update the view
            [item _updateView];
        }
}
@end

One can even create some pretty cool effects:

Red Tab Bar
(source: booleanmagic.com)

It is very possible that Apple will reject an application for doing this. If the private API is removed in a future OS update,
-[UITabBar recolorItemsWithColor:shadowColor:shadowOffset:shadowBlur:] will do nothing instead of crashing.


Adding gradient is very simple, add the following lines of code:


CGFloat components[8] = {0.0,0.4,1.0,0.2,0.0,0.6,1.0,1.0};
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();  
CGGradientRef colorGradient = CGGradientCreateWithColorComponents(colorSpace, components, NULL, 2);
CGContextDrawLinearGradient(cxt, colorGradient,CGPointZero,CGPointMake(0,contextRect.size.height),0);

This will get you very close to what Apple does on the tabbar but, not exact. To get there, just add two more points/colors in components and instead of NULL in CGGradientCreateWithColorComponents, use something like {0,0.5,0.6,1.0}. In fact, all you need is one background color and three alpha points (with color part being all 1s, since you just need shading while retaining a single color profile).

I will post my code if this isn't clear ... cheers.


It's been almost a year but here is the code. Add this as a category to UIImage or convert to class-wide. Remember, the image you are passing (self) has to be an alpha only image (the mask is created based on the visible parts of the image).



- (UIImage *) imageWithBackgroundColor:(UIColor *)bgColor 
                           shadeAlpha1:(CGFloat)alpha1 
                           shadeAlpha2:(CGFloat)alpha2
                           shadeAlpha3:(CGFloat)alpha3 
                           shadowColor:(UIColor *)shadowColor 
                          shadowOffset:(CGSize)shadowOffset 
                            shadowBlur:(CGFloat)shadowBlur { 

    UIImage *image = self;

    CGColorRef cgColor = [bgColor CGColor];
    CGColorRef cgShadowColor = [shadowColor CGColor];

    CGFloat components[16] = {1,1,1,alpha1,1,1,1,alpha1,1,1,1,alpha2,1,1,1,alpha3};
    CGFloat locations[4] = {0,0.5,0.6,1};

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();  

    CGGradientRef colorGradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, (size_t)4);

    CGRect contextRect;
    contextRect.origin.x = 0.0f;
    contextRect.origin.y = 0.0f;
    contextRect.size = [image size];
    //contextRect.size = CGSizeMake([image size].width+5,[image size].height+5);  
    // Retrieve source image and begin image context
    UIImage *itemImage = image;
    CGSize itemImageSize = [itemImage size];
    CGPoint itemImagePosition; 
    itemImagePosition.x = ceilf((contextRect.size.width - itemImageSize.width) / 2);
    itemImagePosition.y = ceilf((contextRect.size.height - itemImageSize.height) / 2);
    UIGraphicsBeginImageContext(contextRect.size);
    CGContextRef c = UIGraphicsGetCurrentContext();
    // Setup shadow
    CGContextSetShadowWithColor(c, shadowOffset, shadowBlur, cgShadowColor);
    // Setup transparency layer and clip to mask
    CGContextBeginTransparencyLayer(c, NULL);
    CGContextScaleCTM(c, 1.0, -1.0);
    CGContextClipToMask(c, CGRectMake(itemImagePosition.x, -itemImagePosition.y, itemImageSize.width, -itemImageSize.height), [itemImage CGImage]);
    // Fill and end the transparency layer
    CGContextSetFillColorWithColor(c, cgColor);     
    contextRect.size.height = -contextRect.size.height;
    CGContextFillRect(c, contextRect);
    CGContextDrawLinearGradient(c, colorGradient,CGPointZero,CGPointMake(contextRect.size.width*1.0/4.0,contextRect.size.height),0);
    CGContextEndTransparencyLayer(c);
    //CGPointMake(contextRect.size.width*3.0/4.0, 0)
    // Set selected image and end context
    UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    CGColorSpaceRelease(colorSpace);
    CGGradientRelease(colorGradient);

    return resultImage;

}

For example, the following will produce an effect very similar to what the native tabbar does:



UIImage *niceImage = [[UIImage imageNamed:@"image_name"] imageWithBackgroundColor:[UIColor colorWithRed:41.0/255.0 green:147.0/255.0 blue:239.0/255.0 alpha:1.0] 
                                                                      shadeAlpha1:0.6 
                                                                      shadeAlpha2:0.0 
                                                                      shadeAlpha3:0.4 
                                                                      shadowColor:[UIColor blackColor] 
                                                                     shadowOffset:CGSizeMake(0.0f, -1.0f)  
                                                                       shadowBlur:3.0]; 


There is a solution to this using a custom implemented tab bar at the iDev Recipes site.

http://idevrecipes.com/2011/01/04/how-does-the-twitter-iphone-app-implement-a-custom-tab-bar