Android開發擷取手機的螢幕寬高,density值,px 寬高,dp 的寬高,及px 和dp互轉

來源:互聯網
上載者:User

直接貼代碼

tvModel.setText(android.os.Build.MODEL);//手機型號

// 擷取螢幕密度(方法1)
int screenWidth1 = getActivity().getWindowManager().getDefaultDisplay().getWidth();       // 螢幕寬(像素,如:480px)
int screenHeight1 = getActivity().getWindowManager().getDefaultDisplay().getHeight();      // 螢幕高(像素,如:800p)

tvScreenHeight1.setText(screenHeight1 + " px");
tvScreenWidth1.setText(screenWidth1 + " px");


// 擷取螢幕密度(方法2)
DisplayMetrics dm2 = getResources().getDisplayMetrics();

float density = dm2.density;        // 螢幕密度(像素比例:0.75/1.0/1.5/2.0)
int densityDPI = dm2.densityDpi;     // 螢幕密度(每寸像素:120/160/240/320)
float xdpi = dm2.xdpi;
float ydpi = dm2.ydpi;

int screenWidth2 = dm2.widthPixels;      // 螢幕寬(像素,如:480px)
int screenHeight2 = dm2.heightPixels;     // 螢幕高(像素,如:800px)

tvScreenHeight2.setText(screenHeight2 + " px");
tvScreenWidth2.setText(screenWidth2 + " px");
tvScreenDensity2.setText(density + "");
tvScreenDensityDPI2.setText(densityDPI + "");

// 擷取螢幕密度(方法3)
DisplayMetrics dm3 = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm3);

density = dm3.density;      // 螢幕密度(像素比例:0.75/1.0/1.5/2.0)
densityDPI = dm3.densityDpi;     // 螢幕密度(每寸像素:120/160/240/320)
xdpi = dm3.xdpi;
ydpi = dm3.ydpi;

tvScreenDensity3.setText(density + "");
tvScreenDensityDPI3.setText(densityDPI + "");

int screenWidth3 = dm3.widthPixels;          // 螢幕寬(px,如:480px)
int screenHeight3 = dm3.heightPixels;        // 螢幕高(px,如:800px)

tvScreenHeight3.setText(screenHeight3 + " px");
tvScreenWidth3.setText(screenWidth3 + " px");

float screenWidthDip = (dm3.widthPixels / density);    // 螢幕寬(dip,如:320dip)
float screenHeightDip = (dm3.heightPixels / density);   // 螢幕寬(dip,如:533dip)

tvScreenHeight4.setText(screenHeightDip + " dip");
tvScreenWidth4.setText(screenWidthDip + " dip");

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.