From Pixel to dp & sp — How to convert px to dp & sp manually in Android
In this post, I will explain how we can convert the size of a design in Pixel to Density-independent pixels (Dp) or Scale-independent pixels (Sp) using in Android Development.
In mobile development, we work with a lot of tools. And I think, Figma is one of the most common tools that probably, we work with it everyday.
But with only design mode, we cannot get the size for Android development. And from 171px in Figma, how many Dp was it?
I. Understand the design
Here for quick view over the design, I will use Figma as the tool for measure px. This should be the same with other design tools.
When you start to create a blank screen with Figma. We can choose from the frame tool. It provides several of options that you can choose
For example, here I selected the iPhone 16 pro. And it return a frame with 402x874.
But the real size of an iPhone 16 pro is 1206x2622.
Here is why: Figma design use Logical resolution of the screen, not the full physical pixel resolution. And in fact, Apple devices use a 3x Rentina scale factor (meaning the actual screen has 3 times more physical pixels per logical pixel). So if we 3x(Figma’s screen size) we can have the Physical resolution of the device.
II. PPI (Pixels Per Inch)
We can calculate this number easily by Pythagorean theorem:
Here we have W = 402 and H = 874 and Screen Diagonal of iPhone 16 pro is 6.3-inch. So the PPI ≈ 153
III. Density
In Android, we have a concept of Density:
the pixel density of a device screen, meaning the number of pixels that fit into a square inch of the display, often measured in “dots per inch” (dpi)
And the formula to get Density value:
With 160 is the dpi baseline. Which is on that baseline, 1px = 1dp.
From this, we can calculate the density of this iPhone 16 pro is ≈ 0.956
IV. Density-independent pixels (Dp)
From the above numbers, we now can convert the px to dp by using the formula:
A view with size in pixel: 234x124 now equal in dp: ≈ 245x130
Here is the design with iPhone 16 pro with Google Pixel 4 screen shoot
V. Scale density & Scale-independent pixels (Sp)
scaledDensity = density × fontScale
In Figma design for iPhone screen, the default font scale is 1.0.
So the scaled density here is the density x 1.0 = density
From previous part, the density ≈ 0.956
With text size = 20px ≈ 21sp
Now, you have the overall view about how pixel transform to dp and sp. Hope you guys having some more understand about screen display units in Android. Thanks for reading!