Difference between android dimension: pt and dp

前端 未结 7 1899
迷失自我
迷失自我 2020-11-30 18:28

The documentation says that 160 dp (density-independent) equals 1 inch. And 72 pt is also 1 inch. So I don\'t see why android define a dp measurement while it seems to work

相关标签:
7条回答
  • 2020-11-30 19:19

    The documentation says that 160 dp (density-independent) equals 1 inch. And 72 pt is also 1 inch.

    The nuance here is that 160 dp (or dip) is roughly 1 inch, while 72 pt is exactly 1 inch. The difference is how android converts both units to pixels, which depends on the screen density of the device.


    A single dp is a single px on a device at 160 dpi. Android uses the "density bucket" the device falls into, and multiplies a scaler to convert dp to px.

    Bucket | DPI | Scaler
    ---------------------
    ldpi   | 120 | 0.75
    mdpi   | 160 | 1.00
    tvdpi  | 213 | 1.33
    hdpi   | 240 | 1.50
    xhdpi  | 320 | 2.00
    xxhdpi | 480 | 3.00
    

    dp to px converts following this formula: dp * scaler = px.


    A single pt is exactly 1/72 of an inch on any screen density. Android converts pt to px using the exact dpi (xdpi and ydpi) of the device's screen.

    pt to px converts following this formula: pt / 72 * dpi = px.


    So I don't see why android define a dp measurement while it seems to work the same as points. Can anybody explain that? Why should I use dp if I can use pt?

    Take an example, display 160 dp and 72 pt on a 160 dpi device. A 160 dpi device falls into the mdpi density bucket, with a scaler of 1.0. Use the formulas above to convert to px.

    160 dp * 1.0 = 160 px
    72 pt / 72 * 160 = 160 px
    

    What about on a 170 dpi device? A 170 dpi device falls into the mdpi density bucket, with a scaler of 1.0.

    160 dp * 1.0 = 160 px
    72 pt / 72 * 170 = 170 px
    

    What about on a 150 dpi device? A 150 dpi device falls into the mdpi density bucket, with a scaler of 1.0.

    160 dp * 1.0 = 160 px
    72 pt / 72 * 150 = 150 px
    

    The moral of the story is, dp keeps exact dimensions and helps keep performance, allowing some physical size variation depending on device density. On the other hand, pt is exactly the same physical size on every density, which leads to a different amount of px being used, which can hinder performance and cause aliasing and artifacts if used on images. dp is recommended unless absolutely exact physical dimensions are required (you have a ruler on screen, etc).

    I have written an in depth blog on Android's dimension units, which gives more info and sample code - Understanding Density Independence in Android

    0 讨论(0)
提交回复
热议问题