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

android中dip、dp、px、sp和屏幕密度

2011-07-21 16:39 411 查看
 1. dip: density-independent pixel(密度无关像素). 不同设备有不同的显示效果,这个和设备硬件有关,一般我们为了支持WVGA、HVGA和QVGA 推荐使用这
    这个,不依赖像素。
    这里要特别注意dip与屏幕密度有关,而屏幕密度又与具体的硬件有关,硬件设置不正确,有可能导致dip不能正常显示。在屏幕密度为160的显示屏上,1dip=1px,有时候可能你的屏幕分辨率很大如480*800,但是屏幕密度没有正确设置比如说还是160,那么这个时候凡是使用dip的都会显示异常,基本都是显示过小。
     dip的换算:
           dip(value)=(int) (px(value)/1.5 + 0.5)
2. dp: 很简单,和dip是一样的。
3. px: pixels(像素),不同的设备不同的显示屏显示效果是相同的,这是绝对像素,是多少就永远是多少不会改变。
4.  sp: scaled pixels(放大像素). 主要用于字体显示best for textsize。
 NOTE: 根据google的推荐,像素统一使用dip,字体统一使用sp  
/**
* 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类中的解释,160dpi的设备作为基准,其它的根据这个来进行缩放。如密度为320的,则缩放因子为320/160=2.0;如密度为120,则因子为120/160=0.75。
在缩放因子为1的设备上,1dp=1px;
在缩放因子为2的设备上,1dp=2px;
如此类推。

在一些设备上,X方向和Y方向的密度不一样,如X方向的密度可能是1.5,Y方向的密度是2.0,这样一来我们在适配手机屏幕时就需要根据X,Y的密度分别来设置。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android google