Reputation: 183
Using the code below, I've added a background image to a UINavigationController (the view, NOT the nav bar) and I'm trying to scale the image to fill the view, because I don't know the user's device and orientation. (Note: I do NOT want to create device- or orientation-specific sizes / resolution because my background images could change so this would take too much time).
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"%@", NSStringFromCGRect(self.navigationController.view.frame));
// Set background image
NSString *filename = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"assets/images/wallpaper.jpg"];
self.background = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:filename]];
self.background.contentMode = UIViewContentModeScaleAspectFill;
self.background.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
self.background.center = CGPointMake(CGRectGetMidX(self.navigationController.view.frame), CGRectGetMidY(self.navigationController.view.frame));
[self.navigationController.view insertSubview:self.background atIndex:0];
}
The UIViewContentModeScaleAspectFill and UIViewAutoresizingFlexibleHeight/Width is SUPPOSED to make the image scale to fill the screen regardless of screen size and orientation. However, I need help with an issue on the simulator: iOS behaves differently depending on whether the simulator is started in portrait / landscape mode.
The image below shows what happens when the app is started in portrait mode and then rotated to landscape. In portrait, the image is NOT scaled to fill the view (there are black bars above/below the image). In landscape, the image is correctly scaled to fill the view.
The image below shows what happens when the app is started in landscape and then rotated to portrait. In landscape, the image is NOT scaled to fill the view (there are black bars to the sides of the image). In portrait, the image is correctly scaled to fill the view.
Why is iOS handling these two scenario's differently, why is the image NOT scaling correctly to fill the view and how do I get UIViewContentModeScaleAspectFill to work correctly?
Upvotes: 2
Views: 222
Reputation: 2277
Reposting my comment as an answer so you can mark this question as solved.
You're not setting the UIImageView
's initial frame
. Try something like
- (void)viewDidLoad
{
[super viewDidLoad];
...
self.background.frame = self.navigationController.view.bounds;
[self.navigationController.view insertSubview:self.background atIndex:0];
}
Upvotes: 1