In Android development, when it comes to screen video problems, the conversion between PX, DP, SP is an important part, so Yang Brother a tool class for everyone.
Package com.zw.express.tool;
Import Android.content.Context;
Import Android.util.DisplayMetrics;
/**
* YDC
* @author Administrator
*
*/
public class Densityutils {
/**
* Switch from Dip unit to PX (pixel) According to the resolution of the phone
*/
public static int dp2px (context context, float Dpvalue) {
Displaymetrics DM = context.getresources (). Getdisplaymetrics ();
Final float scale = dm.density;
return (int) (Dpvalue * scale + 0.5f);
}
/**
* According to the resolution of the phone from PX (pixel) to the unit to become DP
*/
public static float PX2DP (context context, float Pxvalue) {
Displaymetrics DM = context.getresources (). Getdisplaymetrics ();
Final float scale = dm.density;
Return (pxvalue-0.5f)/scale;
}
/**
* Convert PX value to SP value, keep text size unchanged
*/
public static int PX2SP (context context, float Pxvalue) {
Final float Fontscale = context.getresources (). Getdisplaymetrics (). scaleddensity;
return (int) (Pxvalue/fontscale + 0.5f);
}
/**
* Convert SP value to PX value, keep text size unchanged
*/
public static int sp2px (context context, float Spvalue) {
Final float Fontscale = context.getresources (). Getdisplaymetrics (). scaleddensity;
return (int) (Spvalue * fontscale + 0.5f);
}
}
Android Unit conversion (Conversion tool class between PX, DP, SP)