
Introduction
This is just a note for myself to remind me how to do dp-to-pixel translation and vice versa. Let’s see how to do it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public static float convertDpToPixel(float dp, Context context) { float px = dp * getDensity(context); return px; }
public static float convertPixelToDp(float px, Context context) { float dp = px / getDensity(context); return dp; }
public static float getDensity(Activity context) { DisplayMetrics metrics = new DisplayMetrics(); context.getWindowManager().getDefaultDisplay().getMetrics(metrics); return metrics.density; }
|
It’s pretty simple, enjoy.
Happy Coding.
[Reference]
- DisplayMetrics | Android Developers
- Screen compatibility overview | Android Developers
- Pixplicity | DP/PX converter