arm1.ru

How to detect a Retina Display on iPad/iPhone

Note! If you just need to figure out what kind of screen your iPad, iPhone, or iPod has, simply follow this link: https://arm1.ru/retina/

While trying to figure out how to detect the presence of a Retina display on a device in Objective-C, I had to do some googling. I found this solution and am writing it down here as a cheat sheet.

Get the screen bounds:

CGRect screenBounds = [[UIScreen mainScreen] bounds];

It returns the screen size, usually 320x480; even on iPhone 4, iPhone 4S, and iPod Touch it will still return 320x480 (apparently because old apps would otherwise crash). For iPad it returns 768x1024 — both on iPad/iPad 2 and on the new iPad with Retina Display.

Get the screen scale:

CGFloat screenScale = [[UIScreen mainScreen] scale];

It returns 1.0f for all non-Retina screens. It returns 2.0f for Retina screens. This applies to all iOS devices.

So, having screen dimensions characteristic of the form factor (phone/iPod or tablet) and knowing the scale, we can calculate the device’s actual screen size:

CGSize screenSize = CGSizeMake(screenBounds.size.width * screenScale, screenBounds.size.height * screenScale);

If you run code like this:

CGRect screenBounds = [[UIScreen mainScreen] bounds];
NSLog(@"%f x %f", screenBounds.size.width, screenBounds.size.height);
    
CGFloat screenScale = [[UIScreen mainScreen] scale];
NSLog(@"%f", screenScale);
    
CGSize screenSize = CGSizeMake(screenBounds.size.width * screenScale, screenBounds.size.height * screenScale);
NSLog(@"%f x %f", screenSize.width, screenSize.height);

then you will see all dimensions in the console. In this case, I ran it on the iPad Retina simulator:

Как определить Retina Display на iPad/iPhone

And then, by checking the dimensions/device type, you can substitute the required graphics at the required sizes. Profit.

P.S. As for images, you only need to create 2 files: for example, "image.png" and the same image at double size named "image@2x.png", and then use only the first one. For example:

[UIImage imageNamed:@"image.png"];

If the device has Retina, the app will automatically pick up the higher-resolution file (image@2x.png).

keyboard_return