How to stretch background image in UINavigationBar and UITabBar when autoresist

I set the background image with rounded corners for UINavigationBar and UITabBar, however during rotation the backgrondimage repeats rather than stretches. Is there any way to stretch so that the corners remain rounded?

Thanks!

+4
source share
4 answers

for ios5.0+ use [UIImage imageNamed:nil] resizableImageWithCapInsets] .

+7
source

Found it [UIImage imageNamed:nil] stretchableImage...] etc.

+4
source

The accepted answer does not work for me on iOS 11 and iPhone X (simulator) when I install resizableImageWithCapInsets:UIEdgeInsetsZero . The other answer stretchableImage... seems to work, but does not provide a complete solution. So, I would like to share what I have, after several tests with the API:

First, consider the source code:

 [[UITabBar appearance] setBackgroundImage:[UIImage imageNamed:@"Tab BG"]]; [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"Nav BG"] forBarMetrics:UIBarMetricsDefault]; 

I found that this works on iPhone 7 and iPhone 7 plus if-and-only - if the PNG files @ 2x and @ 3x correspond to the exact width of these two resolutions, i.e. 750 pixels (375pt) and 1242 pixels (414 pt). Since iPhone SE uses @ 2x PNG with 640 pixels (320 pixels), the right side of the image is cropped. On iPhone X, the height is no longer the same as that of another iPhone, resulting in an image with vertical tiles.

In my situation, it is best to stretch my background both horizontally and vertically (stretch to a suitable one). So my solution creates a stretchable image without covers:

 [[UITabBar appearance] setBackgroundImage:[[UIImage imageNamed:@"Tab BG"] stretchableImageWithLeftCapWidth:0 topCapHeight:0]]; [[UINavigationBar appearance] setBackgroundImage:[[UIImage imageNamed:@"Nav BG"] stretchableImageWithLeftCapWidth:0 topCapHeight:0] forBarMetrics:UIBarMetricsDefault]; 

I tested it on an iPhone X simulator.

+2
source

use this code to stretch the background image using autoresist

 UIImageView *navBarBG = [UIImageView alloc] init]; UIImage *navBarBg = [UIImage imageNamed:@"navBarImg"]; UIImage *background = [navBarBg stretchableImageWithLeftCapWidth:13 topCapHeight:22]; [navBarBG setImage:background]; navBarBG.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; 

You can specify LeftCapWidth and topCapHeight to suit your needs.

0
source

Source: https://habr.com/ru/post/1386474/


All Articles