How to find PPI programmatically with precision

Durai Amuthan.H picture Durai Amuthan.H · Apr 14, 2016 · Viewed 7.6k times · Source

I am trying to find out PPI(Pixels Per Inch) in iOS.

I couldn't find any direct way to query this like we do for display size

UIScreen.mainScreen().bounds

There is a way to do it by multiplying scale with standard generic PPI for iPhone(163) or iPad(132) but it's not accurate.

If the formula is right then PPI of iPhone 6 plus is 489 but in reality the PPI is 401 Here is the reference

For now it seems like hardcoding is the way to go.

But I'd like to do it programmatically using a formula.

Answer

Jens Schwarzer picture Jens Schwarzer · Oct 3, 2017

I have just ported and updated one of my old ObjC libraries to Swift. You can use it or take parts of the code you need. Get it here: https://github.com/marchv/UIScreenExtension.

The library uses UIScreen.main.nativeScale to convert from Pixels Per Inch (PPI) to Points Per Inch.

Install the library using Cocoapods and then import it:

import UIScreenExtension

And then make use of it:

if let pointsPerCentimeter = UIScreen.pointsPerCentimeter {
   // code
}