Set the background image of UINavigationBar

the ios version <= ios 4.3

mehod 1:create a category and implement this method:

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx 
{
   if([self isMemberOfClass:[UINavigationBar class]])
   {
     UIImage *image = [UIImage imageNamed:@"navBarBackground.png"];
     CGContextClip(ctx);
     CGContextTranslateCTM(ctx, 0, image.size.height);
     CGContextScaleCTM(ctx, 1.0, -1.0);
     CGContextDrawImage(ctx,
     CGRectMake(0, 0, self.frame.size.width, self.frame.size.height), image.CGImage);
   }
   else
   {        
     [super drawLayer:layer inContext:ctx];    
   }
}  

Method 2 create a category and implement this method:

- (void)drawRect:(CGRect)rect
{
  static UIImage *image;
  if (!image) {
    image = [UIImage imageNamed: @"HeaderBackground.png"];
    if (!image) image = [UIImage imageNamed:@"DefaultHeader.png"];
  }
  if (!image) return;
  CGContextRef context = UIGraphicsGetCurrentContext();
  CGContextDrawImage(context, CGRectMake(0, 0, self.frame.size.width, self.frame.size.height), image.CGImage);
}

Mehod 3 create a category and implement this method:

-(void) setBackgroundImage:(UIImage*)image withTag:(NSInteger)bgTag{
if (image == NULL) {
return;
}
UIImageView *aTabBarBackground = [[UIImageView alloc]initWithImage:image];
aTabBarBackground.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
aTabBarBackground.tag = bgTag;
[self addSubview:aTabBarBackground];
[self sendSubviewToBack:aTabBarBackground];
[aTabBarBackground release];
}

-(void) resetBackground:(NSInteger)bgTag {

[self sendSubviewToBack:[self viewWithTag:bgTag]];
}

ios 5:

[navigationbar  setBackgroundImage:[UIImage imageNamed:@"background.png"] forBarMetrics:UIBarMetricsDefault];

posted @ 2011-09-28 12:28  harvey.ding  阅读(267)  评论(0)    收藏  举报