How to find PPI programmatically with precision

2020-07-03 07:22发布

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.

3条回答
来,给爷笑一个
2楼-- · 2020-07-03 07:41

I believe there is no public API to get either PPI or physical size of a screen.

The only way is to hardcode list of devices with their physical sizes and/or PPI's (and you can get a device type out of UIDevice class).

BTW. Here is the question which is pretty much ask the same thing (different way): How do ruler apps stay accurate on all devices?

查看更多
淡お忘
3楼-- · 2020-07-03 07:48

iPhone Plus has scale 3, but nativeScale is 2.6.

UIKit samples this content down to fit the actual screen dimensions. Metal or OpenGL ES contents should be rendered at the precise dimensions.

int screenPPI() {
    return [[UIScreen mainScreen] nativeScale] * ((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? 132 : 163);
}
查看更多
在下西门庆
4楼-- · 2020-07-03 07:57

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
}
查看更多
登录 后发表回答