How to find PPI programmatically with precision

一曲冷凌霜 提交于 2020-06-24 22:01:53

问题


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.


回答1:


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
}



回答2:


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:


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);
}


来源:https://stackoverflow.com/questions/36618965/how-to-find-ppi-programmatically-with-precision

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!