Android dp to px and px to dp, simple unit conversion java function.
Need some career advice or prepping for an Android developer interview? Hit me up on Topmate.io, and let's chat!
Android dp to px
The method in the code below converts
context: Context to get resources and device specific display metric.
The following function returns a float value to represent px equivalent to dp depending on device density
public static float convertDpToPixel(float dp, Context context){
return dp * ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}
Android pixel to dp
This method converts device specific pixels to density independent pixels (dp).
px: A value in px (pixels) unit. Which we need to convert into db.
context: Context to get resources and device specific display metrics
The following function returns a float value to represent dp equivalent to px value.
public static float convertPixelsToDp(float px, Context context){
return px / ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}
Source: StackOverflow