Wednesday, September 21, 2011

How to Create Custom Background for UINavigationBar

Needed a custom background for UINavigationBar (pre-iOS5). First tried placing an UIImageView under "Black Translucent" UINavigationBar, but there were some problems:

Custom image was not visible enough by default. Changing navigation bar alpha value to make background more visible made title and buttons less visible. For a while I tried to find the "perfect" balance, but finally gave up. Fortunately.

Here's the solution I'm using in one of my own apps:
@implementation UINavigationBar (CustomImage)
- (void)drawRect:(CGRect)rect
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGColorRef fillColor = [[UIColor colorWithPatternImage:[UIImage imageNamed:@"tile.png"]] CGColor];
    CGContextSetFillColorWithColor(context, fillColor);
    CGContextFillRect(context, self.bounds);
It's a UINavigationBar class category overwriting drawRect. Please check answers at Stack Overflow to my question "Custom background under transparent UINavigationBar" for other solutions and tips.

Works just fine for me, even though I'm a bit graphically limited. Well ok, used more time to create that graphics and have to admit I kind of like it!

No comments:

Post a Comment