How to convert pixels to dip (density independent pixels) in Android

In my Android app, I have pixels (69 pixels) and I need to convert these pixels to dip (density independent pixels).

Any suggestions?

+6
source share
3 answers

I hope it will be useful

Resources r = getResources(); float dp = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 69, r.getDisplayMetrics()); 
+7
source

Just divide your pixel value by DisplayMetrics.density.

+10
source

You can try the following:

 public int convertDiptoPx(int pixel){ float scale = getResources().getDisplayMetrics().density; int dips=(int) ((pixel * scale) + 0.5f); logMessage("Px=" +pixel+" DipValue="+dips ); return dips; } 

Editted:

  public int convertPxtoDip (int pixel) {
     float scale = getResources (). getDisplayMetrics (). density;
     int dips = (int) ((pixel / scale) + 0.5f);
     return dips;
 }
+7
source

Source: https://habr.com/ru/post/912873/


All Articles