21

Anyone know if there's a way to get the screen density (ppi) of the device at runtime? It'd be nice to not have to hard code the different densities in case apple switches it up in the future...

MZamkow
  • 305
  • 1
  • 2
  • 6

2 Answers2

24

I've been hunting this down for too long, and there doesn't seem to be an easy way to get the dpi. However, the documentation for UIScreen says an unscaled point is about equal to 1/160th of an inch.

So, basically if you want the dpi, you could multiply the scale by 160.

  float scale = 1;
  if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
    scale = [[UIScreen mainScreen] scale];
  }
  float dpi = 160 * scale;

(The if statement with respondsToSelector is to keep the code working for older versions of iOS that don't have that property available)

According to Wikipedia, the iPhone is 163 dpi, an iPhone with a retina display is 326, and the iPad is 132. So the iPad's dpi isn't particularly accurate using this formula, although the iPhone's is pretty good. If you want more accuracy for known devices, you could hardcode the dpi for known devices, with a 1/160 ratio as a fallback for anything in the future.

  float scale = 1;
  if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
    scale = [[UIScreen mainScreen] scale];
  }
  float dpi;
  if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
    dpi = 132 * scale;
  } else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
    dpi = 163 * scale;
  } else {
    dpi = 160 * scale;
  }

This isn't really ideal, and I wouldn't mind seeing a better solution myself, but it's the best I could find.

max
  • 676
  • 1
  • 5
  • 10
  • 1
    this does not work for iPad mini, which has 163 dpi, but is idiom iPad – AlexWien Mar 31 '13 at 15:21
  • @AlexWien Did you find a solution to this issue? – Mike Weir Apr 13 '13 at 19:09
  • @PhoenixX_2 yes, but there is no perfect solution it works only for all ipad minis yet known. itvworks by get machine id. search here for "detect iPad mini" – AlexWien Apr 13 '13 at 19:11
  • 1
    If the formula is right then **PPI** of **iPhone 6 plus is 489** but in reality the **PPI is 401** Here is the reference http://www.alphr.com/apple/apple-iphone-6/7076/iphone-6-vs-iphone-6-plus-screen-comparison – Durai Amuthan.H Apr 19 '16 at 12:32
4

Try https://github.com/lmirosevic/GBDeviceInfo

int ppi = [GBDeviceInfo deviceInfo].displayInfo.pixelsPerInch;                // #> 326]

Works on iOS and OSX

JH95
  • 489
  • 1
  • 7
  • 24
  • 4
    those ppi values are also hardcoded into that Kit. If you look at the code you will find ` // 6 Plus @[@7, @1]: @[@(GBDeviceModeliPhone6Plus), @"iPhone 6 Plus", @(GBDeviceDisplay5p5Inch), @401],` – ben Mar 02 '17 at 08:01