Android開發中dp,sp和px之間的轉換

來源:互聯網
上載者:User

標籤:return   span   ret   res   dimen   app   bsp   sp2   resources   

本文轉載於 http://blog.csdn.net/student9128/article/details/53932470

眾所周知,在Android開發中dp和px,sp和px之間的轉換時必不可少的,下面將轉換的代碼記錄下來:

 1 public class DisplayUtils { 2     /** 3      * convert px to its equivalent dp 4      *  5      * 將px轉換為與之相等的dp 6      */ 7     public static int px2dp(Context context, float pxValue) { 8         final float scale =  context.getResources().getDisplayMetrics().density; 9         return (int) (pxValue / scale + 0.5f);10     }11 12 13     /**14      * convert dp to its equivalent px15      * 16      * 將dp轉換為與之相等的px17      */18     public static int dp2px(Context context, float dipValue) {19         final float scale = context.getResources().getDisplayMetrics().density;20         return (int) (dipValue * scale + 0.5f);21     }22 23 24     /**25      * convert px to its equivalent sp 26      * 27      * 將px轉換為sp28      */29     public static int px2sp(Context context, float pxValue) {30         final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;31         return (int) (pxValue / fontScale + 0.5f);32     }33 34 35     /**36      * convert sp to its equivalent px37      * 38      * 將sp轉換為px39      */40     public static int sp2px(Context context, float spValue) {41         final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;42         return (int) (spValue * fontScale + 0.5f);43     }44 

同時系統也提供了TypedValue類協助我們轉換

 1 /** 2 * convert dp to its equivalent px 3 */ 4 protected int dp2px(int dp){ 5         return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,getResources().getDisplayMetrics()); 6     } 7  8 /** 9 * convert sp to its equivalent px10 */11 protected int sp2px(int sp){12         return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp,getResources().getDisplayMetrics());13     }

 

 

 

Android開發中dp,sp和px之間的轉換

相關文章

聯繫我們

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