繁体   English   中英

iOS 导航视图背景图像 UIViewContentModeScaleAspectFill 不起作用

[英]iOS navigation view background image UIViewContentModeScaleAspectFill not working

使用下面的代码,我向 UINavigationController(视图,而不是导航栏)添加了背景图像,并且我尝试缩放图像以填充视图,因为我不知道用户的设备和方向。 (注意:我不想创建特定于设备或方向的尺寸/分辨率,因为我的背景图像可能会改变,所以这会花费太多时间)。

- (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];
}

无论屏幕大小和方向如何,UIViewContentModeScaleAspectFill 和 UIViewAutoresizingFlexibleHeight/Width 都应该使图像缩放以填充屏幕。 但是,我需要帮助解决模拟器上的一个问题:iOS 的行为取决于模拟器是否以纵向/横向模式启动。

下图显示了当应用以纵向模式启动然后旋转到横向时会发生什么。 在纵向中,图像不会缩放以填充视图(图像上方/下方有黑条)。 在横向中,图像被正确缩放以填充视图。

图片1

下图显示了当应用程序在横向启动然后旋转到纵向时会发生什么。 在横向中,图像不会缩放以填充视图(图像两侧有黑条)。 在纵向中,图像被正确缩放以填充视图。

图像2

为什么 iOS 处理这两种情况的方式不同,为什么图像不能正确缩放以填充视图以及如何让 UIViewContentModeScaleAspectFill 正常工作?

重新发布我的评论作为答案,以便您可以将此问题标记为已解决。

您没有设置UIImageView的初始frame 尝试类似的东西

- (void)viewDidLoad
{
    [super viewDidLoad];

    ...

    self.background.frame = self.navigationController.view.bounds;
    [self.navigationController.view insertSubview:self.background atIndex:0];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM