I have been trying to figure out how to display a background image behind a UINavigationBar
on my iPhone app and have come across the same solution many times which is as follows:
@implementation UINavigationBar (UINavigationBarCategory) {
- (void)drawRect:(CGRect)rect {
UIImage *img = [UIImage imageNamed: @"logo_bar.png"];
CGContextRef context = UIGraphicsGetCurrentContext();
CGCon开发者_JAVA百科textDrawImage(context, CGRectMake(0, 0, 317, 27), img.CGImage);
}
@end
Which works to a degree
My image is upside down and backwards!! why on earth would that be? I have checked the image itself which is fine. Where would this transform be getting applied??
I also have further questions, like:
How can I choose to show the BG image or perhaps toggle its alpha on selected screens? There is one particular screen where there is a back button and it covers the image, which I dont want, I would rather just not display the image on that screen.
The image is not the entire height of the
UINavigationBar
its just a small slice of it (27 as you can see). How can I keep the tint color for the rest of the bar using this technique?
Thanks, I have not used Categories before which may be key to me understanding this, but perhaps not...
// Drawing code
CGContextRef c = UIGraphicsGetCurrentContext();
UIImage *back=[UIImage imageNamed:@"bar.png"];
CGContextScaleCTM(c,1,-1);
CGContextTranslateCTM(c,0,-44);
CGContextDrawImage(c,CGRectMake(0, 0, 320, 44),[back CGImage]);
This is how I draw my custom navigation bar. Hope that helps.
You can also do it in the drawLayer:inContext: method in a UINavigationBar category class. Inside the drawLayer:inContext: method, you can draw the background image you want to use. This code also supports both portrait and landscape orientations.
- (void) drawLayer:(CALayer *)layer inContext:(CGContextRef)context
{
if ([self isMemberOfClass:[UINavigationBar class]] == NO) {
return;
}
UIImage *image = (self.frame.size.width > 320) ?
[UINavigationBar bgImageLandscape] : [UINavigationBar bgImagePortrait];
CGContextClip(context);
CGContextTranslateCTM(context, 0, image.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, CGRectMake(0, 0, self.frame.size.width, self.frame.size.height), image.CGImage);
}
And this complete demo Xcode project on customizing the appearance of UINavigationBar might be helpful.
精彩评论