我错过了什么设置iOS背景?

时间:2013-09-27 16:36:44

标签: iphone ios ipad uiimageview background-image

我有:

[一系列if语句将backgroundImage设置为[UIImageNamed @“Background-Default-Landscape”];我是否正确地假设如果它是Retina显示器,设备将查找名为Background-Default-Landscape@2x.png的文件?]

UIImageView *backgroundView = [[UIImageView alloc] initWithImage:backgroundImage];
CGRect containerRect = CGRectZero;
containerRect.size = [backgroundImage size];
UIView *containerView = [[UIView alloc] initWithFrame:containerRect];
[containerView addSubview:backgroundView];

现在我的应用程序正在启动,一旦加载显示白色屏幕,而不是指定的背景(没有背景为纯白色)。

在我开始将放在背景上之前,我想要画一个背景,在代码的下方是什么?

谢谢,

- 编辑 -

就代码而言,我有:

- (void) renderScreen
{
    int height = [[UIScreen mainScreen] bounds].size.height;
    int width = [[UIScreen mainScreen] bounds].size.width;

    UIImage *backgroundImage = nil;

    if (height == 2048 || height == 2008 || height == 1024 || height == 1004 || height == 984)
    {
        backgroundImage = [UIImage imageNamed:@"Background-Default-Portrait"];
    }

    // Other such statements cut. 
    UIImageView *backgroundView = [[UIImageView alloc] initWithImage:backgroundImage];
    CGRect containerRect = CGRectZero;
    containerRect.size = [backgroundImage size];
    UIView *containerView = [[UIView alloc] initWithFrame:containerRect];

    [containerView addSubview:backgroundView];
    [self.view addSubview:containerView];

然后在下面是要在背景上绘制的陈述。

在初始视图加载和旋转时调用此方法:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self renderScreen];
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(renderScreen) name:UIDeviceOrientationDidChangeNotification object:nil];
}

行为是正确的初始屏幕加载,然后它变为白色,之后似乎没有任何有趣的事情发生。

- 编辑 -

在顶部,我有:

int height = [[UIScreen mainScreen] bounds].size.height;
int width = [[UIScreen mainScreen] bounds].size.width;

当我NSLog高度和宽度时,对于横向模式的视网膜设备,我得到1024的高度和768的宽度。显示的图像是肖像图像的旋转;如果我在侧面转动设备,图像整齐地填满整个屏幕,但背景显示水平挤压图像。

我应该做些什么不同才能正确获得高度和宽度?我希望横向设备的高度为768,宽度为1024.

1 个答案:

答案 0 :(得分:1)

每次renderScreen触发时,它都会向当前控制器的主视图添加两个子视图:

[containerView addSubview:backgroundView];
[self.view addSubview:containerView];

每次旋转设备时都会闪光。

至少将containerView作为属性并替换它。

@property (nonatomic, strong) UIView *containerView;

并在 - (void)renderScreen

[self.containerView  removeFromSuperview];
self.containerView = [[UIView alloc] initWithFrame:containerRect];
[self.view addSubview:self.containerView];

您还可以添加:

[self.view setNeedsDisplay];

以便重新绘制视图。