Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Dp to Px converter and vice-versa

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 385
    Comment on it

    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: