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...
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.
Try https://github.com/lmirosevic/GBDeviceInfo
int ppi = [GBDeviceInfo deviceInfo].displayInfo.pixelsPerInch; // #> 326]
Works on iOS and OSX
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With