Android Pixel Calculator

dp

Density-independent Pixels

sp

Scale-independent Pixels

px

Pixels

mm

Millimeters

pt

Points

in

Inches

 


Check relation between the dp, px, sp, in, mm and pt measurement units and convert to other unit.

 in
@

Android doesn't do direct pixel mapping, it uses Density Independent Pixel (dpi) values to scales the actual screen size

to calculate pixel density - getResources().getDisplayMetrics().density;

Screen density is area of pixel quantity or total count of pixels in the vertical and horizontal directions. This pixel area measurement is referred to as dpi(dots per inch). In Android, densities categorized in 6 types:

ldpi (low) ~120dpi
mdpi (medium) ~160dpi
hdpi (high) ~240dpi
xhdpi (extra-high) ~320dpi
xxhdpi (extra-extra-high) ~480dpi
xxxhdpi (extra-extra-extra-high) ~640dpi

The ratio between dpi measurement are following
ldpimdpihdpixhdpixxhdpixxxhdpi

There are other measurement units require for handling like images, graph, layout etc for android app development. In this tool you can compare measurement unit among different measurement unit values

Kotlin

fun dpToPx(dp: Float, context: Context): Float {
    val scale = context.resources.displayMetrics.density
    return dp * scale
}

fun spToPx(sp: Float, context: Context): Float {
    val scale = context.resources.displayMetrics.scaledDensity
    return sp * scale
}

fun ptToPx(pt: Float, context: Context): Float {
    return pt * (1.0f / 0.75f)
}

fun inToPx(inch: Float, context: Context): Float {
    val dpi = context.resources.displayMetrics.densityDpi
    return inch * dpi
}

fun mmToPx(mm: Float, context: Context): Float {
    val inch = mm / 25.4f
    return inToPx(inch, context)
}

Java

public class UnitConverter {

    public static float dpToPx(float dp, Context context) {
        float scale = context.getResources().getDisplayMetrics().density;
        return dp * scale;
    }

    public static float spToPx(float sp, Context context) {
        float scale = context.getResources().getDisplayMetrics().scaledDensity;
        return sp * scale;
    }

    public static float ptToPx(float pt, Context context) {
        return pt * (1.0f / 0.75f);
    }

    public static float inToPx(float inch, Context context) {
        int dpi = context.getResources().getDisplayMetrics().densityDpi;
        return inch * dpi;
    }

    public static float mmToPx(float mm, Context context) {
        float inch = mm / 25.4f;
        return inToPx(inch, context);
    }
}

resources