Skip to content

Instantly share code, notes, and snippets.

@nesterchung
Forked from laaptu/DpToPxAndPxToDp
Created October 14, 2016 04:36
Show Gist options
  • Save nesterchung/516d91e6e10bcca02a91b53b65accf66 to your computer and use it in GitHub Desktop.
Save nesterchung/516d91e6e10bcca02a91b53b65accf66 to your computer and use it in GitHub Desktop.
Android convert dp to px and vice versa
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);
}
//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
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));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment