This article is reproduced in http://blog.csdn.net/student9128/article/details/53932470
It is well known that the conversion between DP and PX,SP and PX is essential in Android development, and the following code is recorded:
1 Public classDisplayutils {2 /**3 * Convert PX to its equivalent DP4 * 5 * Convert px to equal DP6 */7 Public Static intPX2DP (Context context,floatpxvalue) {8 Final floatScale =context.getresources (). Getdisplaymetrics (). density;9 return(int) (Pxvalue/scale + 0.5f);Ten } One A - /** - * Convert DP to its equivalent PX the * - * Converts the DP to an equal PX - */ - Public Static intDP2PX (Context context,floatdipvalue) { + Final floatScale =context.getresources (). Getdisplaymetrics (). density; - return(int) (Dipvalue * scale + 0.5f); + } A at - /** - * Convert px to its equivalent SP - * - * Convert px to SP - */ in Public Static intPX2SP (Context context,floatpxvalue) { - Final floatFontscale =context.getresources (). Getdisplaymetrics (). scaleddensity; to return(int) (Pxvalue/fontscale + 0.5f); + } - the * /** $ * Convert SP to its equivalent PXPanax Notoginseng * - * Convert SP to px the */ + Public Static intSP2PX (Context context,floatspvalue) { A Final floatFontscale =context.getresources (). Getdisplaymetrics (). scaleddensity; the return(int) (Spvalue * Fontscale + 0.5f); + } -
The system also provides the Typedvalue class to help us convert
1 /**2 * Convert DP to its equivalent PX3 */4 protected intDP2PX (intDP) {5 return(int) typedvalue.applydimension (Typedvalue.complex_unit_dip, Dp,getresources (). Getdisplaymetrics ());6 }7 8 /**9 * Convert SP to its equivalent PXTen */ One protected intSP2PX (intsp) { A return(int) typedvalue.applydimension (typedvalue.complex_unit_sp, Sp,getresources (). Getdisplaymetrics ()); -}
Conversion between DP,SP and PX in Android development