In Android, the unit conversion between dip (dp) and px is dip2px dp to px without context algorithm (and to obtain the screen width and height), and androiddip2px
Let's talk a little bit about the Code:
1. dip2px dp to px without context Algorithm
public static int px2dip(int pxValue){final float scale = Resources.getSystem().getDisplayMetrics().density;return (int) (pxValue / scale + 0.5f);}public static float dip2px(float dipValue){final float scale = Resources.getSystem().getDisplayMetrics().density;return (dipValue * scale + 0.5f);}
2. Obtain the screen area
/*** Obtain the screen area */public static Rect getScreenRect () {DisplayMetrics displayMetric = new DisplayMetrics (); displayMetric = Resources. getSystem (). getDisplayMetrics (); Rect rect = new Rect (0, 0, displayMetric. widthPixels, displayMetric. heightPixels); return rect;}/*** get screen width **/public static int getScreenWidth () {return getScreenRect (). width ();}/*** get screen height **/public static int getScreenHeight () {return getScreenRect (). height ();}