android中像素單位dp、px、pt、sp的比較

來源:互聯網
上載者:User

android中像素單位dp、px、pt、sp的比較
dp(dip): device independent pixels(裝置獨立像素). 不同裝置有不同的顯示效果,這個和裝置硬體有關,一般我們為了支援WVGA、HVGA和QVGA 推薦使用這個,不依賴像素。 px: pixels(像素). 不同裝置顯示效果相同,一般我們HVGA代表320x480像素,這個用的比較多。 pt: point,是一個標準的長度單位,1pt=1/72英寸,用於印刷業,非常簡單易用; sp: scaled pixels(放大像素). 主要用於字型顯示best for textsize。 由此,根據 google 的建議,TextView 的字型大小最好使用 sp 做單位,而且查看TextView的源碼可知 Android 預設使用 sp 作為字型大小單位。  還有, google代碼裡邊所用的單位都是以px為預設單位的.  apk的資源套件中,當螢幕density=240時使用hdpi標籤的資源 當螢幕density=160時,使用mdpi標籤的資源 當螢幕density=120時,使用ldpi標籤的資源。 在每英寸160點的顯示器上,1dp = 1px。  下面是幾種不同單位的相互轉換.  public static int dip2px(Context context, float dipValue){ final float scale = context.getResources().getDisplayMetrics().density; return (int)(dipValue * scale + 0.5f); } public static int px2dip(Context context, float pxValue){ final float scale = context.getResource().getDisplayMetrics().density; return (int)(pxValue / scale + 0.5f); } public static int dip2px(Context context, float dipValue){ final float scale = context.getResources().getDisplayMetrics().density; return (int)(dipValue * scale + 0.5f); } public static int px2dip(Context context, float pxValue){ final float scale = context.getResource().getDisplayMetrics().density; return (int)(pxValue / scale + 0.5f); } 下面說下如何擷取解析度:     在一個Activity的onCreate方法中,寫入如下代碼:        DisplayMetrics metric = new DisplayMetrics();        getWindowManager().getDefaultDisplay().getMetrics(metric);        int width = metric.widthPixels;  // 螢幕寬度(像素)        int height = metric.heightPixels;  // 螢幕高度(像素)        float density = metric.density;  // 螢幕密度(0.75 / 1.0 / 1.5)        int densityDpi = metric.densityDpi;  // 螢幕密度DPI(120 / 160 / 240)     在 Android 中,  1pt 大概等於 2.22sp 以上供參考,如果 UI 能夠以 sp 為單位提供設計是最好的,如果設計中沒有 sp的概念,則開發人員也可以通過適當的換算取近似值。 過去,程式員通常以像素為單位設計電腦使用者介面。例如,定義一個寬度為300像素的表單欄位,列之間的間距為5個像素,表徵圖大小為16×16像素 等。這樣處理的問題在於,如果在一個DPI(dpi)更高的新顯示器上運行該程式,則使用者介面會顯得很小。在有些情況下,使用者介面可能會小到難以看清 內容。與解析度無關的度量單位可以解決這一問題。 Android支援下列所有單位。px(像素):螢幕上的點。in(英寸):長度單位。mm(毫米):長度單位。pt(磅):1/72英寸。dp(與密度無關的像素):一種基於螢幕密度的抽象單位。在每英寸160點的顯示器上,1dp = 1px。dip:與dp相同,多用於android/ophone樣本中。sp(與刻度無關的像素):與dp類似,但是可以根據使用者的字型大小喜好設定進行縮放。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.