Android手機適配,手機尺寸、px、dpi、dp、sp詳解

轉載請註明出處:http://blog.csdn.net/z191726501/article/details/50411483

最近一直在學習Android的適配問題,在學習的過程中發現很多博客抄來抄去,並沒有什麼實質的東西,因此決定將自己關於Android手機適配問題的學習筆記整理出來,希望都夠幫助到大家。

要學習Android的適配問題,以下幾個概念是必須要理解的。

px:像素,pixel的縮寫。這個應該不需要過多解釋,平常我們所說的手機的分辨率爲1920x1080,這裏的單位用的就是px,也就是說高爲1920個像素,寬爲1080個像素。

手機尺寸:這個大家也不陌生,就是手機斜對角線的長度。Nexus 5的尺寸爲4.95英寸,其實指的就是斜對角之間的距離。

dpi:dots per inch 每英寸上像素的點數,它的計算方式爲(手機斜對角線上的像素數/手機尺寸)。比如谷歌的親兒子Nexus 5的分辨率爲1920x1080,手機尺寸爲4.95英寸。那麼此款手機的DPI就是(1920*1920+ 1080*1080)½/4.95≈445dpi。

dip或者簡寫爲dp:device independent pixels 設備獨立像素(也有人將d理解爲density,將dip翻譯成密度無關像素,不過個人認爲還是翻譯成設備獨立像素比較好,畢竟TypedValue類中聲明COMPLEX_UNIT_DIP這個變量時就是將d翻譯爲device),谷歌推薦佈局使用的單位。

sp:scaled pixels 可縮放的像素,谷歌推薦字體使用的單位。

上面簡單介紹了一下幾個概念的意思,接下來咱們就要弄清楚幾個問題:

1.我們知道Android資源文件下有這樣幾個目錄,ldpi、mdpi、hdpi、xhdpi、xxhdpi、xxxhdpi,它們與dpi有什麼關係?

2.dp、sp和px之間又有什麼關係?

關於第一個問題我們有必要來看一下DisplayMetrics這個類,這個類中定義了一些常量,讓我們來一起看一下都是些什麼常量:

 

    /**
     * Standard quantized DPI for low-density screens.
     */
    public static final int DENSITY_LOW = 120;

    /**
     * Standard quantized DPI for medium-density screens.
     */
    public static final int DENSITY_MEDIUM = 160;

    /**
     * This is a secondary density, added for some common screen configurations.
     * It is recommended that applications not generally target this as a first
     * class density -- that is, don't supply specific graphics for this
     * density, instead allow the platform to scale from other densities
     * (typically {@link #DENSITY_HIGH}) as
     * appropriate.  In most cases (such as using bitmaps in
     * {@link android.graphics.drawable.Drawable}) the platform
     * can perform this scaling at load time, so the only cost is some slight
     * startup runtime overhead.
     *
     * <p>This density was original introduced to correspond with a
     * 720p TV screen: the density for 1080p televisions is
     * {@link #DENSITY_XHIGH}, and the value here provides the same UI
     * size for a TV running at 720p.  It has also found use in 7" tablets,
     * when these devices have 1280x720 displays.
     */
    public static final int DENSITY_TV = 213;

    /**
     * Standard quantized DPI for high-density screens.
     */
    public static final int DENSITY_HIGH = 240;

    /**
     * Standard quantized DPI for extra-high-density screens.
     */
    public static final int DENSITY_XHIGH = 320;

    /**
     * Intermediate density for screens that sit somewhere between
     * {@link #DENSITY_XHIGH} (320 dpi) and {@link #DENSITY_XXHIGH} (480 dpi).
     * This is not a density that applications should target, instead relying
     * on the system to scale their {@link #DENSITY_XXHIGH} assets for them.
     */
    public static final int DENSITY_400 = 400;

    /**
     * Standard quantized DPI for extra-extra-high-density screens.
     */
    public static final int DENSITY_XXHIGH = 480;

    /**
     * Intermediate density for screens that sit somewhere between
     * {@link #DENSITY_XXHIGH} (480 dpi) and {@link #DENSITY_XXXHIGH} (640 dpi).
     * This is not a density that applications should target, instead relying
     * on the system to scale their {@link #DENSITY_XXXHIGH} assets for them.
     */
    public static final int DENSITY_560 = 560;

    /**
     * Standard quantized DPI for extra-extra-extra-high-density screens.  Applications
     * should not generally worry about this density; relying on XHIGH graphics
     * being scaled up to it should be sufficient for almost all cases.  A typical
     * use of this density would be 4K television screens -- 3840x2160, which
     * is 2x a traditional HD 1920x1080 screen which runs at DENSITY_XHIGH.
     */
    public static final int DENSITY_XXXHIGH = 640;

    /**
     * The reference density used throughout the system.
     */
    public static final int DENSITY_DEFAULT = DENSITY_MEDIUM;

    /**
     * Scaling factor to convert a density in DPI units to the density scale.
     * @hide
     */
    public static final float DENSITY_DEFAULT_SCALE = 1.0f / DENSITY_DEFAULT;

    /**
     * The device's density.
     * @hide because eventually this should be able to change while
     * running, so shouldn't be a constant.
     * @deprecated There is no longer a static density; you can find the
     * density for a display in {@link #densityDpi}.
     */
    @Deprecated
    public static int DENSITY_DEVICE = getDeviceDensity();

 

首先,咱們看到了第一個定義的常量是DENISTY_LOW。咦,好巧,咱們的ldpi中l不就是low的縮寫嗎?接着往下看,第9行定義了MEDIUM,33行定義了HIGH,38行定義了XHIGH,51行定義了XXHIGH,68行定義了XXXHIGH,至此咱們所有的文件目錄都找到了相對應的值。也就是說,當手機dpi爲120時就會去加載ldpi目錄下的資源,依次類推,手機dpi爲160時會去加載mdpi目錄下的資源,等等。至於其它的幾個值比如TV、400一般情況下大家不會用到,講起來也比較麻煩,所以就不做解釋了。

OK,這幾個目錄所對應的的dpi的值咱們搞清楚了,接下來咱們來看一下第二個問題,dp、sp和px之間到底有着什麼關係。

其實咱們在佈局文件中寫的寬和高的值都會先調用TypedValue類中的applyDimension()方法進行一次轉換,那麼這個方法是幹什麼用的呢,讓我們先看一下它的源碼:

    /**
     * Converts an unpacked complex data value holding a dimension to its final floating 
     * point value. The two parameters <var>unit</var> and <var>value</var>
     * are as in {@link #TYPE_DIMENSION}.
     *  
     * @param unit The unit to convert from.
     * @param value The value to apply the unit to.
     * @param metrics Current display metrics to use in the conversion -- 
     *                supplies display density and scaling information.
     * 
     * @return The complex floating point value multiplied by the appropriate 
     * metrics depending on its unit. 
     */
    public static float applyDimension(int unit, float value,
                                       DisplayMetrics metrics)
    {
        switch (unit) {
        case COMPLEX_UNIT_PX:
            return value;
        case COMPLEX_UNIT_DIP:
            return value * metrics.density;
        case COMPLEX_UNIT_SP:
            return value * metrics.scaledDensity;
        case COMPLEX_UNIT_PT:
            return value * metrics.xdpi * (1.0f/72);
        case COMPLEX_UNIT_IN:
            return value * metrics.xdpi;
        case COMPLEX_UNIT_MM:
            return value * metrics.xdpi * (1.0f/25.4f);
        }
        return 0;
    }


根據註釋,不難理解,這個方法的作用是將對應的值轉化爲實際屏幕上的點值,也就是像素值。此方法接受三個參數,第一個爲單位的類型,第二個爲數值,第三個爲DisplayMetrics對象,可以使用Resources.getSystem().getDisplayMetrics()獲得。

 

既然知道了這個方法是將各種單位轉化爲像素,那咱們就先來看一下傳入dp的話系統是怎麼給咱們轉換成px的吧。

首先,第17行會對傳入的參數類型進行一個判斷,如果是dp的話進進入第20行的判斷條件,返回的值爲咱們傳進的值value*metrics.density。

那麼metrics.density的值爲多少呢?咱們再來看一下DisplayMetrics這個類,這次咱們看到它有一個setToDefaults()方法:

 

public void setToDefaults() {
        widthPixels = 0;
        heightPixels = 0;
        density =  DENSITY_DEVICE / (float) DENSITY_DEFAULT;
        densityDpi =  DENSITY_DEVICE;
        scaledDensity = density;
        xdpi = DENSITY_DEVICE;
        ydpi = DENSITY_DEVICE;
        noncompatWidthPixels = widthPixels;
        noncompatHeightPixels = heightPixels;
        noncompatDensity = density;
        noncompatDensityDpi = densityDpi;
        noncompatScaledDensity = scaledDensity;
        noncompatXdpi = xdpi;
        noncompatYdpi = ydpi;
    }


從名字上判斷出,這是一個賦值方法。在這個方法中的第4行咱們可以看到給density賦值爲DENSITY_DEVICE / (float) DENSITY_DEFAULT。我靠,又是這麼巧,我記得剛剛咱們看DisplayMetrics類中定義常量的代碼中是有這兩個值的!事不宜遲,咱們回過頭來再看一下DisplayMetrics類中定義常量的代碼。第89行定義了DENSITY_DEVICE 的值爲getDeviceDensity(),其實就是拿到的就是咱們手機本身的dpi。第73行定義了DENSITY_DEFAULT的值爲DENSITY_MEDIUM也就是160。

 

到現在,咱們終於能夠總結出dp和px的換算公式了:px = (手機本身的dpi / 160)  * dp。比如某款手機的dpi爲320,那麼5dp所對應的的px= (320/160) * 5 = 10px。

接下來咱們再來看一下sp與px的換算。還是TypedValue類中的applyDimension()方法,直接來到第22行,可以看到類型爲sp時px的值爲values*metrics.scaledDensity。接下來再找到DisplayMetrics類的setToDefaults()方法,來到第6行,scaledDensity=density ,接下來咱們來看一下density是什麼。恩?等等,density?這個名字怎麼那麼熟悉啊?剛剛dp與px是怎麼換算的來着?趕緊回過頭來看一下TypedValue類中的applyDimension()方法,直接來到第21行。Oh My God!咱們看到了什麼!當單位是dp時px = value*metrics.density,當單位是sp時px = values*metrics.scaledDensity,而且scaledDensity=density !好了不用我多說了,我想大家都明白了,搞了半天原來dp和sp是一回事啊。

但是,它們真的一樣嗎?如果真的一模一樣的話谷歌爲什麼自找麻煩搞出來sp這個單位,直接用一個dp不是更省事嗎?而且sp爲什麼叫做scaled pixels?

其實默認情況下咱們認爲sp和dp一致是沒有問題的,不過不知道大家記不記得在手機的“系統設置”的“顯示”中可以修改字體的大小。沒錯,默認情況下,字體大小爲“普通”,這時候dp和sp兩個單位保持一致。但當修改了字體大小之後,所有以sp爲單位的字體都會進行相應的縮放(具體的縮放比例參見我的另一篇博客Android系統設置大號字體後佈局錯亂的問題),所以谷歌推薦的字體單位的名字才叫做sp(scaled pixels)。

除了上面這種情況還有一種情況會導致sp與dp不一致。正如大家知道的那樣,Android是開源的,開源到所有的手機廠商都可以定製自己的系統。所以,當手機廠商定製了屬於自己的字體之後,也會導致這兩個單位有偏差。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章