4

I am trying to change the background image for my navigation bar using setBackgroundImage: forBarMetrics: in my setting method.

Problem is the image doesn't fit onto the bar, looks like the image is stretched at least double the original size...

The image size is 320 x 44...

I tried rename image to @2x, but it didn't change a thing...

I tried assign this image to navigationItem.titleView but the view got cut off on the edge...

does any one have hint how to set the image so that it won't get stretched?

UINavigationBar *naviBar = [self.navigationController navigationBar];
UIImage *img = [UIImage imageNamed:@"NavBar02@2x.png"];
[naviBar setBackgroundImage:img forBarMetrics:UIBarMetricsDefault];

Thanks in advance

The iOSDev
  • 5,237
  • 7
  • 41
  • 78
Chris Lin
  • 709
  • 2
  • 10
  • 20
  • codes added, please take a look thanks! – Chris Lin Jul 20 '12 at 10:20
  • NO!!! Don't rename the image to "@2x". Never do that, you will always use the non-retina version of the image for UI elements. The "@2x" is for iOS to automatically use instead of low resolution imagery if the device has a retina screen. – Mick MacCallum Jul 20 '12 at 10:43

3 Answers3

14

ok i got it finally!

problem: navigation bar takes images thats 320 x 44 pixels, since each point in iPhone is 2 pixels, if you are using points for navigation bar, the image that you use will look like its stretched 4 times (2x for y, and 2x for x coordinate).

to solve it, simply add file extension @2x to your image file (e.g. yourImgName@2x.png). You must rename it BEFORE you drag into Xcode! it will NOT work if you try to rename it in Xcode.

ps. DO NOT include @2x in your code, just the file name like so [UIImage imageNamed: @"yourImgName.png"]

hope this helps

Chris Lin
  • 709
  • 2
  • 10
  • 20
  • Only retina iPhone takes 2 pixels for each point. That's why you need to prepare two sets of assets. – Selkie Jul 25 '12 at 03:07
  • Thanks a lot for sharing. My problem was that I was renaming the @2x inside xCode. And iOS wouldn't set the scale of my image to 2. Thanks – pedros Jan 30 '13 at 20:01
  • So what does everyone think about just providing a retina display version and allowing it to be scaled down for non retina? I've tried this and the retina image looks fine in non retina phone. – The Muffin Man May 23 '13 at 04:17
  • 1
    What happens if you create this image with [UIImage imageWithData:data] and thus there never is any filename for the image? How do you specify the normal image vs the @2x image? – Mike Apr 17 '15 at 20:02
1

You should have two image. One is 320x44 pixles and name as NavBar02.png. Another is 640x88 pixels and name as NavBar02@2x.png.

iOS will select the suitable image based on device's resolution.

Selkie
  • 1,773
  • 1
  • 14
  • 21
0

for all icons, apple recommends the following. image sizes for navigation and tab bars.

To resize, open your image in Preview. go to

tools -> adjust size.

Hope that helps.

Ryan B.
  • 99
  • 2
  • 14