Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
633 views
in Technique[技术] by (71.8m points)

objective c - Get ppi of iPhone / iPad / iPod Touch at runtime

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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;

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...