天天看點

android中px,sp,dp之間互相轉化的工具類

在平時開發中,難免遇到需要在代碼裡對尺寸進行轉化的問題,在這裡總結一下,友善以後調用

public class DensityUtil {

   /**
     * dp轉換成px
     */
    private int dp2px(Context context,float dpValue){
        float scale=context.getResources().getDisplayMetrics().density;
        return (int)(dpValue*scale+0.5f);
    }

    /**
     * px轉換成dp
     */
    private int px2dp(Context context,float pxValue){
        float scale=context.getResources().getDisplayMetrics().density;
        return (int)(pxValue/scale+0.5f);
    }
    /**
     * sp轉換成px
     */
    private int sp2px(Context context,float spValue){
        float fontScale=context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue*fontScale+0.5f);
    }
    /**
     * px轉換成sp
     */
    private int px2sp(Context context,float pxValue){
        float fontScale=context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue/fontScale+0.5f);
    }
}
           

  原文來自:--------------------- 

  https://blog.csdn.net/qidingquan/article/details/53714603?utm_source=copy 

繼續閱讀