Bram - 1 month ago 7x

Android Question

I am trying to calculate a variable amount of pixels to density independent pixels and vice-versa.

This formula

`(px to dp): dp = (int)(px / (displayMetrics.densityDpi / 160));`

This is my dp to px formula:

`px = (int)(dp * (displayMetrics.densityDpi / 160));`

Could someone give me some pointers?

Answer

Note: The widely used solution above is based on `displayMetrics.density`

. However, the docs explain that this value is a rounded value, used with the screen 'buckets'. Eg. on my Nexus 10 it returns 2, where the real value would be 298dpi (real) / 160dpi (default) = 1.8625.

Depending on your requirements, you might need the exact transformation, which can be achieved like this:

[Edit] This is not meant to be mixed with Android's internal dp unit, as this is of course still based on the screen buckets. Use this where you want a unit that should render the same real size on different devices.

Convert dp to pixel:

```
public int dpToPx(int dp) {
DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
return px;
}
```

Convert pixel to dp:

```
public int pxToDp(int px) {
DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
int dp = Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
return dp;
}
```

Note that there are xdpi and ydpi properties, you might want to distinguish, but I can't imagine a sane display where these values differ greatly.

Source (Stackoverflow)

Comments