在运行时获取iPhone / iPad / iPod Touch的ppi [英] Get ppi of iPhone / iPad / iPod Touch at runtime

查看:96
本文介绍了在运行时获取iPhone / iPad / iPod Touch的ppi的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都知道是否有办法在运行时获取设备的屏幕密度(ppi)?如果将来苹果公司将其打开,不必硬编码不同的密度就好了。

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...

推荐答案

我一直在寻找这个问题太久了,似乎没有一个简单的方法来获得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.

这篇关于在运行时获取iPhone / iPad / iPod Touch的ppi的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆