Thursday, 1 September 2011

Android: methods for converting pixels to density-independent pixels, and vice versa

When creating Views or setting heights, widths, margins and so forth of Views programmatically (i.e. not in the xml layout files), the values to set are all in pixels, which is no good when you're trying to work with density-independent pixels (dips). So here's a couple of methods convert from pixels to dips and vice versa should the need arise:

/**
 * Converts the given number of pixels
 * to the corresponding number of density-independent pixels
 * using the formula: dip = px / (dpi / 160).
 */
public static float convertPxToDip(Context context, float pixels) {
 DisplayMetrics dm = context.getResources().getDisplayMetrics();
 return pixels / dm.density; // dm.density gives the scaling factor

 // alternative way of doing it
 // return (pixels * DisplayMetrics.DENSITY_DEFAULT) / (dm.densityDpi);
}

/**
 * Converts the given number of density-independent pixels
 * to the corresponding number of pixels
 * using the formula: px = dip * (dpi / 160).
 */
public static float convertDipToPx(Context context, float dip) {
 DisplayMetrics dm = context.getResources().getDisplayMetrics();
 return dip * dm.density; // dm.density gives the scaling factor

 // alternative way of doing it
 // return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, dm);
}

No comments: