What is density and scaledDensity for on Android?

Question:

What are density and scaledDensity for on Android?

What use can we make of it?

Answer:

I gave the following usage for density once ( scaledDensity I never used):

Imagine that you want to display an image prepared at runtime by you. Customize a picture, for example, and display it in an ImageView of a certain size in density-independent pixels or dip (eg, 32×32 dip ).

Your "paint canvas" starts with a Bitmap instance of a certain width x height, but those dimensions are in pixels, not dpi. On screens with mdpi resolution (where 1 pixel equals 1 dip ) keeping the same sizes works, but on screens with resolution above mdpi a dip is larger than one pixel. If you work on a 32 x 32 pixel image and then throw it into an ImageView , Android will scale the 32 x 32 pixels to 32 x 32 dip , which depending on the screen density will cause the picture to lose a lot of detail.

The solution is to start with a larger Bitmap . How bigger? It will depend on the density of the screen in relation to an mdpi screen.

This is where the field DensityMetrics.density comes in. It is a fractional value ( float ) that represents exactly how much denser the device's screen is than an mdpi screen.

Let's take the Samsung Galaxy S4 as an example, which has a density of approximately 2.755. It means the S4's screen is 2,755 times denser than an mdpi screen. An mdpi screen is on the order of 160 pixels per inch. If we multiply 2.755 by 160 we get approximately 441, which is the number of pixels per inch of the S4. So if we want to correctly display the aforementioned image on an S4, this density will be what we will use to increase the Bitmap , that is, it should be 32 x 2,755 pixels high (rounded up to an integer value when necessary, of course) and the same wide, that is, 88 x 88 pixels. When the Bitmap already prepared by you is used to fill the ImageView , you will see that the image details have been kept.

Scroll to Top