I want to change the pixel to dp, what should I do?

Asked 2 years ago, Updated 2 years ago, 43 views

I want to change the pixel to dp on Android, what should I do with the code?

android

2022-09-22 22:07

1 Answers

public static float convertDpToPixel(float dp, Context context){
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float px = dp * (metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
    return px;
}

public static float convertPixelsToDp(float px, Context context){
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float dp = px / (metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
    return dp;
}


2022-09-22 22:07

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.