简体   繁体   English

如何以dpi获得屏幕宽度?

[英]How to get screen width in dpi?

How can I get the screen width dpi?如何获得屏幕宽度 dpi?

DisplayMetrics metrics = getResources().getDisplayMetrics();
int f = metrics.densityDpi;


  //  getWindowManager().getDefaultDisplay().getMetrics(metrics);

int width = metrics.widthPixels;
int dp = (int)(width / (metrics.density));

I do this, so lets assume my densitydpi is 120..and widthpixel 240.. via calculation i get 240/0.75.... so I have 320 widthdpi?我这样做,所以让我们假设我的 densitydpi 是 120..and widthpixel 240.. 通过计算我得到 240/0.75 .... 所以我有 320 widthdpi?

However that's not the case....widthdpi is smaller then 320 I think...because 320 goes with me wrong in the screen.... using 120 works.然而事实并非如此....widthdpi 比 320 小,我认为...因为 320 在屏幕上与我错误....使用 120 作品。

on Nexus 4...with width 768 and densitydpi 320...I divide 768/2 and i get 384 correct width density dpi (it works)在 Nexus 4 上...宽度为 768,密度为 320...我除以 768/2,得到 384 正确的宽度密度 dpi(它有效)

But on other ones like 240, 160, 120 density dpi..the calculation of width dpi seems wrong ...但在其他像 240, 160, 120 密度 dpi..宽度 dpi 的计算似乎是错误的......

Per the Supporting Multiple Screens guide's definition of DP根据支持多屏幕指南对 DP 的定义

px = dp * (dpi / 160)

Therefore所以

dp = px / (dpi / 160)

or equivalently或等效地

dp = px * 160 / dpi

Remember that dp stands for 'density-independent pixel' - ie, 1dp is the same physical size on a ldpi device as it is on an xxhdpi device.请记住,dp 代表“与密度无关的像素”——即,1dp 在 ldpi 设备上与在 xxhdpi 设备上的物理大小相同。 Therefore you should expect all phones to have roughly ~300-400dp of width, noting the bucket sizes by dp:因此,您应该期望所有手机的宽度大约为 ~300-400dp,注意按 dp 表示的存储桶大小:

  • xlarge screens are at least 960dp x 720dp xlarge 屏幕至少为 960dp x 720dp
  • large screens are at least 640dp x 480dp大屏幕至少 640dp x 480dp
  • normal screens are at least 470dp x 320dp普通屏幕至少为 470dp x 320dp
  • small screens are at least 426dp x 320dp小屏幕至少为 426dp x 320dp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM