What is pixel density?
sobes.tech AI
Answer from AI
Pixel density (density) is the ratio of the number of physical pixels to the number of pixels displayed on the screen (dp or dips). It expresses the number of pixels per inch (dpi) of the screen. A high density means more pixels per inch.
Android uses density to scale UI elements so that they appear approximately the same physical size on screens with different pixel densities.
The main density categories in Android:
| Density category | DPI value | Scaling factor |
|---|---|---|
| ldpi | ~120 | 0.75 |
| mdpi | ~160 | 1.0 |
| hdpi | ~240 | 1.5 |
| xhdpi | ~320 | 2.0 |
| xxhdpi | ~480 | 3.0 |
| xxxhdpi | ~640 | 4.0 |
dp is a unit of measurement based on mdpi (160 dpi), where 1 dp = 1 pixel. On screens with different densities, dp is converted into the corresponding number of physical pixels considering the scaling factor.
For example, on an xhdpi screen (320 dpi, scaling factor 2.0):
1 dp = 2 physical pixels.
Using dp instead of px for sizes and margins in layouts ensures a consistent size of UI elements across different devices. Resources (e.g., images) are also provided in different resource folders (res/drawable-mdpi, res/drawable-hdpi, etc.) to match various densities.
// Example of converting dp to pixels in code
float density = getResources().getDisplayMetrics().density;
int dpValue = 16; // value in dp
int pixelValue = (int) (dpValue * density); // conversion to pixels
<!-- Example of using dp in XML layout -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:textSize="18sp" /> <!-- sp (scaled pixels) is used for fonts and also considers user font size settings -->