px和dp sp的相互转换

import android.content.Context;
import android.util.TypedValue;

public class DPPxUtils {

private DPPxUtils () {
    /* cannot be instantiated */
    throw new UnsupportedOperationException("cannot be instantiated");
}

/**
 * dp转px
 */
public static int dppx(Context context, float dpVal) {
    return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
            dpVal, context.getResources().getDisplayMetrics());
}

/**
 * sp转px
 */
public static int sppx(Context context, float spVal) {
    return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
            spVal, context.getResources().getDisplayMetrics());
}

/**
 * px转dp
 */
public static float pxdp(Context context, float pxVal) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (pxVal / scale);
}

/**
 * px转sp
 */
public static float pxsp(Context context, float pxVal) {
    return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
}

}

你可能感兴趣的:(AndroidAPP,个人笔记,dp,px,dp和px的转换)