2
votes

I'm trying to add a background image to the NavigationBar of an UINavigationBarController

[viewController.navigationBar setBackgroundImage:[UIImage imageNamed:@"NavBarBackground"] forBarMetrics:UIBarMetricsDefault];

In my assets I have a

Apple documentation says about resolutions :

  • iPhone 5/5c/5s/6 @x2 (retina)
  • iPhone 6+ @x3 (retina HD)

BUT

  • iPhone 5(&co) have a screen width of 640px
  • iPhone 6 have a screen width of 750px

How can I handle iPhone 6 case without having another image that I'll need to named with extension in my setBackgroundImage method only for iPhone 6 ?

1

1 Answers

2
votes

The problem is that Navigation Bar on iPhone 6/iPhone 6+ has a different Aspect Ratio comparing to all other iPhone models. So in this case, you need a different Image Set.

But, if the image is just a color background, I suggest using the following code:

[viewController.navigationBar setBackgroundImage:[self imageWithColor:[UIColor greenColor]] forBarMetrics:UIBarMetricsDefaults

And implement the following method:

- (UIImage *)imageWithColor:(UIColor *)color{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}