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());
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章