Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ppi of iPhone / iPad / iPod Touch at runtime

Tags:

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...

like image 820
MZamkow Avatar asked Oct 05 '10 01:10

MZamkow


2 Answers

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.

like image 100
max Avatar answered Nov 19 '22 22:11

max


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

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

Works on iOS and OSX

like image 30
JH95 Avatar answered Nov 19 '22 23:11

JH95