12

Some of my apps use custom images as the background. What is the proper way to check the screen size to place the proper image?

Should it be something like this in viewDidLoad:

if ([UIScreen mainScreen] == 2.0)
{
     UIImage * backgroundImage = [UIImage imageNamed:@"bgimage-568h@2x.png"];
     backgroundImageView = [[UIImageView alloc] initWithImage:backgroundImage]];
}
else
{
    UIImage * backgroundImage = [UIImage imageNamed:@"bgimage.png"];
    backgroundImageView = [[UIImageView alloc] iniWithImage:backgroundImage]];
}

Any tips/advice is much appreciated!

Thanks!

Luke Irvin
  • 1,179
  • 1
  • 20
  • 39

2 Answers2

16

The following code checks the size / bounds of the screen. If the screen is 586 points (remember, that the screen is measured in points because of Retina) than we know that it is the new 4-inch Retina Display.

if ([[UIScreen mainScreen] bounds].size.height == 568)
{
   UIImage * backgroundImage = [UIImage imageNamed:@"bgimage-568h@2x.png"];
   backgroundImageView = [[UIImageView alloc] initWithImage:backgroundImage];
}
else
{
   UIImage * backgroundImage = [UIImage imageNamed:@"bgimage.png"];
   backgroundImageView = [[UIImageView alloc] initWithImage:backgroundImage];
}

See also iOS 6 apps - how to deal with iPhone 5 screen size?

Community
  • 1
  • 1
Bryan
  • 11,398
  • 3
  • 53
  • 78
  • 2
    You can remove the "@2x" and .png text from the image file names and things should work. its usually not a good idea to put "@2x" in there since that's handled under the hood by imageNamed: anyways – Kevlar Sep 26 '12 at 22:44
  • where would this go ? "- viewdidLoad" – Gabriel Oct 07 '12 at 02:44
  • Yes. The code is basically what Luke put in the original question, where he is asking for something to put in `viewDidLoad:` – Bryan Oct 07 '12 at 14:56
1

Bryan's answer above worked for me, except that I had to use

[self.bgImageView setImage:backgroundImage];

rather than

backgroundImageView = [[UIImageView alloc] initWithImage:backgroundImage];

The correct image only displays if I use the former.

alisonc
  • 115
  • 1
  • 8
  • `backgroundImageView` was just a name to illustrate how you write the if-statement. It was put in the question by Luke. Not something you are expected to find in your own program. By the same token, `bgImageView` is just a name in your program, won't work for anyone else unless they happen to have picked the same name. – Bryan Dec 12 '12 at 21:25