As we all know that Android works with dp size.
But what to do if we have px values and want to check corresponding dp value ?. Don't worry try this -
public static int pxToDp(int px, Context ctx) {
DisplayMetrics displayMetrics = ctx.getResources().getDisplayMetrics();
int dp = Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
return dp;
}
public static int dpToPx(int dp, Context ctx) {
DisplayMetrics displayMetrics = ctx.getResources().getDisplayMetrics();
int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
return px;
}
Here we are getting screen size, density, and font scaling from method getDisplayMetrics() and converting it to dp or px.
0 Comment(s)