Android(三) 匹配屏幕密度

  过去,程序员通常以像素为单位设计计算机用户界面。例如:图片大小为80×32像素。这样处理的问题在于,如果在一个dpi(每英寸点数

高的显示器上运行该程序,则用户界面会显得很小。在有些情况下,用户界面可能会小到难以看清内容。由此我们采用与分辨率无关的度量单位来

开发程序就能够解决这个问题。 

一。常用的术语:分清dp与dpi


  (1)px (pixels)像素:每个px对应屏幕上的一个点

  (2)Resolution(分辨率):和电脑的分辨率概念一样,指手机屏幕纵、横方向像素个数

  (3)Density(密度):屏幕里像素值浓度

    (4)dpi(dot per inch) 每英寸像素数:QVGA(Quarter Video Graphics Array)(320*240)分辨率的屏幕物理尺寸是(2英寸*1.5英寸),dpi=160 

  (5)dp或dip(density independent pixels)密度独立像素:一种基于屏幕密度的单位,在每英寸160点的显示器上,1dip=1px

但随着屏幕密度的改变,dip和px的换算会发生改变。这个和设备硬件有关,一般我们为了支持WVGA、HVGA和QVGA 推荐使用这个

换算:px=dp*(dpi/160)

  (6)sp (scaled pixels ) 放大像素:主要处理字体的大小

  (7)in (inches)英寸:标准长度单位

  (8)mm (millimeters)毫米:标准长度单位

  (9)pt (points)点:标准长度单位,1/72 英寸

 二。为什么引入dp

1.不引入dp时

2.引入dp后

设定160dp的长度,相当于告诉Android在160dpi屏幕上显示160px,在240dpi屏幕上显示240px 。

 三。DPI(dot per inch)计算

(1)分辨率480 x 800,屏幕尺寸4.3英寸   216

(2)分辨率540 x 960,屏幕尺寸4.5英寸 244

(3)分辨率240 x 320,屏幕尺寸2.5英寸   160

2.将不同屏幕大小和不同dpi(dot per inch)的设备大致划分为四类,如下图:

三。DisplayMetrics(点击查看源码)

public float 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.

  This value does not exactly follow the real screen size (as given by xdpi and 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).

四。代码

Resources r = getResources(); 
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 14, r.getDisplayMetrics());
public static float convertDpToPixel(float dp, Context context){
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float px = dp * (metrics.densityDpi / 160f);
    return px;
}

public static float convertPixelsToDp(float px, Context context){
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float dp = px / (metrics.densityDpi / 160f);
    return dp;
}
原文地址:https://www.cnblogs.com/yuyutianxia/p/3294139.html