Android DisplayMetrics類獲取屏幕大小


DisplayMetrics

 public class DisplayMetrics 
 extends Object  

java.lang.Object 
   ↳ android.util.DisplayMetrics 
是Android提供的記述屏幕的有關信息的一種結構,諸如其尺寸,密度和字體縮放的一般信息。

第一種方法:

WindowManager wm = (WindowManager) context.getSystemService(
       Context.WINDOW_SERVICE);
DisplayMetrics metrics= new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(metric);

第二種方法

DisplayMetrics metrics= new DisplayMetrics();

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

第三種方法

DisplayMetric metrics=mContext.getResources().getDisplayMetric();

        //這倆個就是手機屏幕的屏幕分辨率,物理寬高值如1080*1920(ToolBar或ActionBar會占據一定空間,得到的heightPiexls會小一點)
        int width = metrics.widthPixels;  // 表示屏幕的像素寬度,單位是px(像素)
        int height = metrics.heightPixels;  // 表示屏幕的像素高度,單位是px(像素)

        float density = metrics.density;  // 顯示器的邏輯密度,Density Independent Pixel(如3.0)

         ( metrics.scaledDensity和metrics.density數值是一樣的)
        int densityDpi = metrics.densityDpi;  // 整個屏幕的像素密度DPI(dots per inch每英寸像素數),可以是密度低,密度中等,或者密度高(如240/ 360 / 480)

        float xdpi= metrics.xdpi /表示在X軸方向上每英寸的像素值,X軸方向上的DPI(dots per inch)
        float ydpi= metrics.ydpi //表示在Y軸方向上每英寸的像素值,  Y方向上的DPI

//wm.getDefaultDisplay().getHeight();獲得的數據和int height = metrics.heightPixels一樣,不過getHeight()方法棄用了,建議使用后者

 

 

density詳細說明

 

float density

 

The logical density of the display. This is a scaling factor for the Density Independent Pixel unit, where one DIP is one pixel on an approximately 160 dpi screen (for example a 240x320, 1.5"x2" screen), providing the baseline of the system's display. Thus on a 160dpi screen this density value will be 1; on a 120 dpi screen it would be .75; etc.

 

This value does not exactly follow the real screen size (as given by xdpi and ydpi, but rather is used to scale the size of the overall UI in steps based on gross changes in the display dpi. For example, a 240x320 screen will have a density of 1 even if its width is 1.8", 1.3", etc. However, if the screen resolution is increased to 320x480 but the screen size remained 1.5"x2" then the density would be increased (probably to 1.5).

不需要在AndroidManifest.xml文件額外聲明 support-screen節點,因為屏幕適配的幾種屬性值都默認為true。參考官方文檔API.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM