且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在运行时获取iPhone / iPad / iPod Touch的ppi

更新时间:2023-01-06 10:59:28

我一直在寻找这个问题太久了,似乎没有一个简单的方法来获得dpi。但是, UIScreen 的文档说未缩放的点大约等于1/160英寸。

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.

所以,基本上如果你想要dpi,你可以将比例乘以160。

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;

(带有respondsToSelector的if语句是为了保持代码适用于不支持旧版iOS的旧版本有这个属性可用)

(The if statement with respondsToSelector is to keep the code working for older versions of iOS that don't have that property available)

根据***,iPhone是163 dpi,带有视网膜显示屏的iPhone是326,iPad是132.所以iPad的dpi是使用这个公式特别准确,虽然iPhone非常好。如果您希望已知设备具有更高的准确度,则可以对已知设备的dpi进行硬编码,将1/160作为未来任何内容的后备。

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.