Android Utililty Methods Pixel to Dip Convert

List of utility methods to do Pixel to Dip Convert

Description

The list of methods to do Pixel to Dip Convert are organized into topic(s).

Method

intpx2sp(Context context, float pxValue)
pxsp
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (pxValue / fontScale + 0.5f);
intpx2sp(Context context, float pxValue)
pxsp
final float scale = getDensity(context);
return (int) (pxValue / scale + 0.5f);
intpx2sp(float pxValue, float fontScale)
pxsp
return (int) (pxValue / fontScale + 0.5f);
intpxToDp(Context context, int pxValue)
Convert px value to dp value
DisplayMetrics displayMetrics = context.getResources()
        .getDisplayMetrics();
return (int) ((pxValue / displayMetrics.density) + 0.5);
intpxToDp(Context ctx, int px)
px To Dp
DisplayMetrics displayMetrics = ctx.getResources()
        .getDisplayMetrics();
int dp = Math.round(px
        / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
return dp;
intpxToSp(Context context, int pxValue)
Convert px value to sp value
DisplayMetrics displayMetrics = context.getResources()
        .getDisplayMetrics();
return (int) ((pxValue / displayMetrics.scaledDensity) + 0.5);
floatgetDpFromPixel(float px, Context context)
This method converts device specific pixels to density independent pixels.
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
return px / (metrics.densityDpi / 160f);
intconvertPxtoDp(Context context, int px)
convert Pxto Dp
float scale = context.getResources().getDisplayMetrics().density;
return (int) (px / scale + 0.5f);
intpx2dip(Context context, int px)
Convert px to dip value
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (px / scale + 0.5f);
intpixelsAsDp(Context context, int sizeInPx)
pixels As Dp
float scale = context.getResources().getDisplayMetrics().density;
return (int) (sizeInPx * scale + 0.5f);