如何获取到Android手机的dp

来自https://www.jianshu.com/p/e0085b03a145

代码:

public void getAndroiodScreenProperty() {
        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;         // 屏幕宽度(像素)
        int height = dm.heightPixels;       // 屏幕高度(像素)
        float density = dm.density;         // 屏幕密度(0.75 / 1.0 / 1.5)
        int densityDpi = dm.densityDpi;     // 屏幕密度dpi(120 / 160 / 240)
        // 屏幕宽度算法:屏幕宽度(像素)/屏幕密度
        int screenWidth = (int) (width / density);  // 屏幕宽度(dp)
        int screenHeight = (int) (height / density);// 屏幕高度(dp)


        Log.d("h_bl", "屏幕宽度(像素):" + width);
        Log.d("h_bl", "屏幕高度(像素):" + height);
        Log.d("h_bl", "屏幕密度(0.75 / 1.0 / 1.5):" + density);
        Log.d("h_bl", "屏幕密度dpi(120 / 160 / 240):" + densityDpi);
        Log.d("h_bl", "屏幕宽度(dp):" + screenWidth);
        Log.d("h_bl", "屏幕高度(dp):" + screenHeight);
    }

 获取屏幕密度

    /**
     * 屏幕密度(0.75 / 1.0 / 1.5)
     * @return
     */
    private float getScreenDensity() {
        DisplayMetrics dm = new DisplayMetrics();
        Objects.requireNonNull(getActivity()).getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.density;
    }

 

posted @ 2020-03-03 01:10  同窗的海生  阅读(1429)  评论(0编辑  收藏  举报