Search code examples
androidandroid-screen-support

Android DP to PX conversion, is 160 dp always 160 px on mdpi?


I'm getting lost in some unfortunate ambiguity regarding http://developer.android.com/guide/practices/screens_support.html, and I can't find a stackoverflow answer that clarifies the issue.

I am well aware of what the documentation claims:

The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, which is the baseline density assumed by the system for a "medium" density screen. At runtime, the system transparently handles any scaling of the dp units, as necessary, based on the actual density of the screen in use. The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels. You should always use dp units when defining your application's UI, to ensure proper display of your UI on screens with different densities.

What is at issue is what their definition of 'dp' is in that formula. Based on the graphic a little further down the page, it seems that "actual density" for an mdpi-class device spans a range of values, from about 120 to about 200. Does that mean that 160 dpi could map to anywhere between 120 to 200 pixels for an mdpi-class device? Or does an mdpi-class device always convert 160 dpi to 160 pixels?


Solution

  • According to this post from Dianne Hackborn, that is indeed the case. A "compatible" Android device cannot have a non-standard density:

    In theory then Android can scale to any density and show its UI to match the exact density of the screen. In practice we don't do this -- we have defined a handful of specific densities we support and require that compatible devices stick to them. Why is this?

    The first reason is just to help our developers. UI designers tend to like to make nice clean graphics; these graphics are drawn as bitmaps, and giving designers a small set of target bitmap sizes to support instead of infinite variation makes things a lot simpler for them.

    (...)

    So Android defines a few major buckets of density values that devices can use, called ldpi (approx 120dpi), mdpi (160 dpi), hdpi (240 dpi), and xhdpi (320 dpi). Manufacturers can select the density that is appropriate for their device, as long as it results in a screen that (after scaling for density) is within the minimum allowed screen size of the platform.