Background image of UINavigationBar doesn't size correctly after orientation change on iPhone 5
Asked Answered
M

1

8

Long title for hopefully a small problem.

I have a UINavigationBar with a custom background image. My app will support landscape orientation as well as portrait. Landscape works well in the simulator for retina 3 inch and non-retina screens. However, on the retina 4 inch screen, the background image is displayed twice its size in landscape mode.

Here's the relevant code snippet from my custom navigation controller's init-method:

[self.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbar-bg.png"] forBarMetrics:UIBarMetricsDefault];        
if (IS_IPHONE_5)
{
    [self.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbar-bg-landscape-iphone5.png"] forBarMetrics:UIBarMetricsLandscapePhone];
}
else
{
    [self.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbar-bg-landscape.png"] forBarMetrics:UIBarMetricsLandscapePhone];
}

IS_IPHONE_5 is a macro defined as:

#define WIDTH_IPHONE_5 568
#define IS_IPHONE_5 ([[UIScreen mainScreen] bounds].size.height == WIDTH_IPHONE_5)

Here 2 screen fragments that might explain things more clearly. When the app opens in portrait mode, everything is fine:

portrait

All blows up when changing to landscape mode:

landscape

The image sizes (in pixels, width x height) for the landscape version of the background image are:

  • navbar-bg-landscape.png: 480x44
  • [email protected]: 960x88
  • navbar-bg-landscape-iphone5.png: 1136x88

Or could it perhaps be a simulator only problem? (I don't have an actual iPhone 5 right now)

Madeup answered 9/10, 2012 at 21:13 Comment(2)
Why are not you using - (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode method to use one image for iphone/ipone5/ipad?Unthinking
Because I didn't know it exists :) Seems promising, might work in my situation. Seems to me this method is only useful if resizing doesn't distort the image though...Madeup
E
7

I believe your navbar-bg-landscape-iphone5.png should actually be called [email protected] and that you should continue to reference it as navbar-bg-landscape-iphone5.png in your code. Because the iPhone 5 has a retina display, iOS will look for the @2x version and use it. If it doesn't find it, it will use the version you have mentioned and then scale it up by 2x. To avoid the 2x scale up by iOS, give it an @2x version.

Erasmoerasmus answered 9/10, 2012 at 21:58 Comment(1)
Yes! I knew it was something small I overlooked. You sir, are a hero ;)Madeup

© 2022 - 2024 — McMap. All rights reserved.