Android中,單位dp、sp、px互相轉換工具類

可以定義一個工具類,用來獲取系統的轉化比值,然後需要使用時調用即可。具體代碼如下:


/**
 * dp、sp轉化工具
 * 
 * @author h55l5
 *
 */
public class DisplayUtil {
    /**
     * 將px轉化爲dip,保證尺寸大小不變
     * 
     * @param context
     * @param pxValue
     * @return dp值
     */
    public static int px2dip(Context context, float pxValue) {
        return (int) (pxValue / getScale(context) + 0.5f);
    }

    /**
     * 將dip值轉化爲對應的px值
     * 
     * @param context
     * @param dipValue
     * @return px值
     */
    public static int dip2px(Context context, float dipValue) {
        return (int) (dipValue * getScale(context) + 0.5f);
    }

    /**
     * 將對應的px值轉化爲sp值
     * 
     * @param context
     * @param pxValue
     * @return 轉化後的sp值
     */
    public static int px2sp(Context context, float pxValue) {
        return (int) (pxValue / getFontScale(context) + 0.5f);
    }

    /**
     * 將對應的sp值轉化爲px值
     * 
     * @param context
     * @param spValue
     * @return 轉化好的px值
     */
    public static int sp2px(Context context, float spValue) {
        return (int) (spValue * getFontScale(context) + 0.5f);
    }

    /**
     * 獲取系統的轉化比例
     * 
     * @param context
     * @return
     */
    private static float getScale(Context context) {
        return context.getResources().getDisplayMetrics().density;
    }

    /**
     * 獲取系統的轉化比例
     * 
     * @param context
     * @return
     */
    private static float getFontScale(Context context) {
        return context.getResources().getDisplayMetrics().scaledDensity;
    }
}

還可以通過系統的方法來進行相關的轉化,具體代碼如下:

public class DisplayUtil {
    public static int dp2px(Context context, int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                context.getResources().getDisplayMetrics());
    }

    public static int sp2px(Context context, int sp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp,
                context.getResources().getDisplayMetrics());
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章