您的位置:首页 > 移动开发 > Android开发

Android之px、dp、sp之间相互转换

2015-12-05 20:15 537 查看
在做Android的UI开发时,通常会用到三种度量单位——px、dp和sp。其中:

px:pixels,像素。不同设备显示效果相同。

dp(dip):device independent pixels,设备独立像素。 不同设备有不同的显示效果,和设备硬件有关,不依赖像素。如果设置表示长度、高度等属性时可以使用dp,与密度无关

sp:scaled pixels,放大像素。主要用于字体显示(best for textsize)。设置字体,需要使用sp,sp除了与密度无关外,还与scale无关。

px、dp和sp之间的相互转换如下:

/**
* 将px值转换为dp(dip)值,保证尺寸大小不变
*
* @param pxValue
* @param scale (DisplayMetrics类中属性density)
* @return
*/
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}


/**
* 将px值转换为sp值,保证文字大小不变
*
* @param pxValue
* @param fontScale (DisplayMetrics类中属性scaledDensity)
* @return
*/
public static int px2sp(Context context, float pxValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (pxValue / fontScale + 0.5f);
}


/**
* 将dp(dip)值转换为px值,保证尺寸大小不变
*
* @param dipValue
* @param scale(DisplayMetrics类中属性density)
* @return
*/
public static int dip2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}


/**
* 将sp值转换为px值,保证文字大小不变
*
* @param spValue
* @param fontScale (DisplayMetrics类中属性scaledDensity)
* @return
*/
public static int sp2px(Context context, float spValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}


其中在DisplayMetrics类中属性density如下定义:

/**
* The logical density of the display.  This is a scaling factor for the
* Density Independent Pixel unit, where one DIP is one pixel on an
* approximately 160 dpi screen (for example a 240x320, 1.5"x2" screen),
* providing the baseline of the system's display. Thus on a 160dpi screen
* this density value will be 1; on a 120 dpi screen it would be .75; etc.
*
* <p>This value does not exactly follow the real screen size (as given by
* {@link #xdpi} and {@link #ydpi}, but rather is used to scale the size of
* the overall UI in steps based on gross changes in the display dpi.  For
* example, a 240x320 screen will have a density of 1 even if its width is
* 1.8", 1.3", etc. However, if the screen resolution is increased to
* 320x480 but the screen size remained 1.5"x2" then the density would be
* increased (probably to 1.5).
*
* @see #DENSITY_DEFAULT
*/
public float density;


在DisplayMetrics类中属性scaledDensity如下定义:

/**
* A scaling factor for fonts displayed on the display.  This is the same
* as {@link #density}, except that it may be adjusted in smaller
* increments at runtime based on a user preference for the font size.
*/
public float scaledDensity;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: