Android 獲取螢幕寬度和高度的幾種方法
阿新 • • 發佈:2020-12-08
轉自:https://www.jianshu.com/p/1a931d943fb4
方法1
Display defaultDisplay = getWindowManager().getDefaultDisplay();
Point point = new Point();
defaultDisplay.getSize(point);
int x = point.x;
int y = point.y;
Log.i(TAG, "x = " + x + ",y = " + y);
//x = 1440,y = 2768
方法2
Rect outSize = new Rect();
getWindowManager().getDefaultDisplay().getRectSize(outSize);
int left = outSize.left;
int top = outSize.top;
int right = outSize.right;
int bottom = outSize.bottom;
Log.d(TAG, "left = " + left + ",top = " + top + ",right = " + right + ",bottom = " + bottom);
//left = 0,top = 0,right = 1440,bottom = 2768
方法3
DisplayMetrics outMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
int widthPixels = outMetrics.widthPixels;
int heightPixels = outMetrics.heightPixels;
Log.i(TAG, "widthPixels = " + widthPixels + ",heightPixels = " + heightPixels);
//widthPixels = 1440, heightPixels = 2768
總結:
-
方法2和方法3檢視原始碼可知其實是一樣的邏輯。
public void getSize(Point outSize) { synchronized (this) { updateDisplayInfoLocked(); mDisplayInfo.getAppMetrics(mTempMetrics, getDisplayAdjustments()); outSize.x = mTempMetrics.widthPixels; outSize.y = mTempMetrics.heightPixels; } } public void getMetrics(DisplayMetrics outMetrics) { synchronized (this) { updateDisplayInfoLocked(); mDisplayInfo.getAppMetrics(outMetrics, getDisplayAdjustments()); } }
方法4
Point outSize = new Point();
getWindowManager().getDefaultDisplay().getRealSize(outSize);
int x = outSize.x;
int y = outSize.y;
Log.w(TAG, "x = " + x + ",y = " + y);
//x = 1440,y = 2960
方法5
DisplayMetrics outMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getRealMetrics(outMetrics);
int widthPixel = outMetrics.widthPixels;
int heightPixel = outMetrics.heightPixels;
Log.w(TAG, "widthPixel = " + widthPixel + ",heightPixel = " + heightPixel);
//widthPixel = 1440,heightPixel = 2960
我們注意到方法1,2,3顯示螢幕的解析度是 1440x2768,而方法4,5顯示的螢幕的解析度是1440x2960。為什麼是這樣了?
- 答:顯示區域以兩種不同的方式描述。包括應用程式的顯示區域和實際顯示區域。
- 應用程式顯示區域指定可能包含應用程式視窗的顯示部分,不包括系統裝飾。 應用程式顯示區域可以小於實際顯示區域,因為系統減去諸如狀態列之類的裝飾元素所需的空間。 使用以下方法查詢應用程式顯示區域:getSize(Point),getRectSize(Rect)和getMetrics(DisplayMetrics)。
- 實際顯示區域指定包含系統裝飾的內容的顯示部分。 即便如此,如果視窗管理器使用(adb shell wm size)模擬較小的顯示器,則實際顯示區域可能小於顯示器的物理尺寸。 使用以下方法查詢實際顯示區域:getRealSize(Point),getRealMetrics(DisplayMetrics)。