float scale = context.getResources().getDisplayMetrics().density;
在分辨率为720*1280的手机上,scale的值为2,对应密度xhdpi
//dp转px
public static int dp2px(Context context, float dpValue) {
float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
//px转dp
public static int px2dp(Context context, float pxValue) {
float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue /scale + 0.5f);
}
//sp转
public static int sp2px(Context context, float spValue) {
float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
网友评论