StackTips
 1 minutes

How to Convert Pixels to Density Independent (DP) Pixels

By Editorial @stacktips, On Sep 17, 2023 Android 2.41K Views

The following code snippet shows how to convert device specific pixels to density independent pixels. It returns a float value to represent dp equivalent to px value

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

Editorial

StackTips provides programming tutorials, how-to guides and code snippets on different programming languages.