StackTips
 1 minutes

Convert DP Unit to Equivalent Pixels in Android

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

The following code snippet shows how to converts DP unit to equivalent pixels, depending on device density. It returns a float value to represent px equivalent to dp depending on device density.

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

Editorial

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