Skip to content

Instantly share code, notes, and snippets.

@SeptiyanAndika
Forked from laaptu/DpToPxAndPxToDp
Last active December 22, 2020 12:51
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save SeptiyanAndika/2d4168310f1d8d0162ac to your computer and use it in GitHub Desktop.
Save SeptiyanAndika/2d4168310f1d8d0162ac to your computer and use it in GitHub Desktop.
//http://stackoverflow.com/questions/4605527/converting-pixels-to-dp
//The above method results accurate method compared to below methods
//http://stackoverflow.com/questions/8309354/formula-px-to-dp-dp-to-px-android
//http://stackoverflow.com/questions/13751080/converting-pixels-to-dpi-for-mdpi-and-hdpi-screens
public static float convertPixelsToDp(float px){
DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
float dp = px / (metrics.densityDpi / 160f);
return Math.round(dp);
}
public static float convertDpToPixel(float dp){
DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
float px = dp * (metrics.densityDpi / 160f);
return Math.round(px);
}
private int convertDpToPx(int dp){
return Math.round(dp*(getResources().getDisplayMetrics().xdpi/DisplayMetrics.DENSITY_DEFAULT));
}
private int convertPxToDp(int px){
return Math.round(px/(Resources.getSystem().getDisplayMetrics().xdpi/DisplayMetrics.DENSITY_DEFAULT));
}
private float dpFromPx(float px)
{
return px / this.getContext().getResources().getDisplayMetrics().density;
}
private float pxFromDp(float dp)
{
return dp * this.getContext().getResources().getDisplayMetrics().density;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment