In Android development, we are accustomed to using DP units in Layout files, but many Java code APIs use PX units (such as setpadding, Setbuttom, Setleft, etc.) by default, which requires us to convert the DP and PX in many scenarios.
The code snippet is as follows:
public class Densityutil { /** * Turns from DP units to px (pixels) * * @param context * @param dpvalue *) based on the resolution of the phone @return * @author shanhy * @date October 28, 2015 * /public static int dip2px (context context, float Dpvalue) { final float scale = context.getresources (). Getdisplaymetrics (). density; return (int) (Dpvalue * scale + 0.5f); } /** * According to the resolution of the phone from px (pixels) to the unit to be DP * * @param context * @param pxvalue * @return * @author SH Anhy * @date October 28, 2015 * /public static int Px2dip (context context, float Pxvalue) { final Float scale = context.getresources (). Getdisplaymetrics (). density; return (int) (Pxvalue/scale + 0.5f); } }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Conversion of PX and DP in Android