android 中 dp和px转换

时间:2022-01-20 16:41:10

DisplayUtils代码:

public class DisplayUtil {

    public static int px2dip(Context context, float px) {
float scale = context.getResources().getDisplayMetrics().density;
return (int) (px / scale + 0.5f);
} public static int dip2px(Context context, float dp) {
float scale = context.getResources().getDisplayMetrics().density;
return (int) (dp * scale + 0.5f);
}
}

Android Framework也提供了相应的工具类供我们使用的。TypedValue 中的 applyDimension() 方法:

/**
*
* @param unit The unit to convert from.
* @param value The value to apply the unit to.
* @param metrics Current display metrics to use in the conversion --
* supplies display density and scaling information.
*/
public static float applyDimension(int unit, float value,
DisplayMetrics metrics)
{
switch (unit) {
case COMPLEX_UNIT_PX:
return value;
case COMPLEX_UNIT_DIP:
return value * metrics.density;
case COMPLEX_UNIT_SP:
return value * metrics.scaledDensity;
case COMPLEX_UNIT_PT:
return value * metrics.xdpi * (1.0f/72);
case COMPLEX_UNIT_IN:
return value * metrics.xdpi;
case COMPLEX_UNIT_MM:
return value * metrics.xdpi * (1.0f/25.4f);
}
return 0;
}

 使用方法:

        //获取10dp
int dp= (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,10,getResources().getDisplayMetrics());
//获取10px
int px= (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX,10,getResources().getDisplayMetrics());
//获取10sp
int sp= (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,10,getResources().getDisplayMetrics());