5

Each Android device has a physical pixel density and a 'quantized density'. Sources state that the quantized density is the one used to determine how drawable-dpi images are selected and scaled at runtime.

Question: precisely how are these images (1) selected and (2) scaled?

For example, a 64x64 image placed into the drawable-xhdpi bucket gets scaled to what size?

Jo Jo
  • 7,245
  • 5
  • 34
  • 49

1 Answers1

10

For the scaling part of the question, first get the quantized density for the device by running

adb shell getprop ro.sf.lcd_density

and call this the quantized density for the device. In general this quantized density differs from the physical density of the device but it can be the same if the physical density falls perfectly as one of the dpi 'bucket' boundaries. Whereas the physical density describes a real-world measurement, the quantized density is set by the device manufacturer, and is usually chosen to be one of the following values:

  • 160
  • 240
  • 320
  • 480

Quantized density controls what I will call the Image Scaling Factor (ISF) for the device. The formula is as follows:

ISF = ro.sf.lcd_density / 160

The ISF is the scale factor that is used when Android's resource-loading/layout-manager reads a resource bitmap from a file and renders it to the screen (I don't know if the scaling happens at load-time or render-time). On the Nexus 6 device, the ISF is 3.5 because the quantized density was set to be 560 (and 560 / 160 = 3.5). To be sure, the rendered size at runtime is also a function of the drawable bucket that contains the file in question. For example, on the Nexus 6:

  • 64-pixel image in mdpi folder renders as 224 pixels (since 3.5*64/1.0 = 224)
  • 64-pixel image in hdpi folder renders as 149 pixels (since 3.5*64/1.5 = 149)
  • 64-pixel image in xhdpi folder renders as 112 pixels (since 3.5*64/2.0 = 112)
  • 64-pixel image in xxhdpi folder renders as 75 pixels (since 3.5*64/3.0 = 75)
  • 64-pixel image in xxxhdpi folder renders as 56 pixels (since 3.5*64/4.0 = 56)

Incidentally, the quantized density also defines the physical size of the dp that you specify in your layout files. The formula for this is:

+=======================+
|          Dq           |
|   1dp = ----- px      |
|          160          |
+=======================+

where Dq is the quantized density. For example,

  • on a device whose Dq is 160, 1dp = 1px
  • on a device whose Dq is 240, 1dp = 1.5px
  • on a device whose Dq is 320, 1dp = 2px
Jo Jo
  • 7,245
  • 5
  • 34
  • 49
  • *Whereas the physical density describes a real-world measurement, the quantized density is set by the device manufacturer, and is usually chosen to be one of the following values:* **This is not true** as I have logged the same and is reported to be 440 in my device which is not either of these 4 – Manish Kumar Sharma Jun 07 '21 at 08:56
  • Right. It is usually chosen to be one of these common values, but it need not be. – Jo Jo Sep 20 '21 at 16:05