android – Converting px (from layout) to dp (applications)

Question:

There is a single screen layout 1080×1920 (smartphone), you need to transfer it to the xml markup of the Android application. Is there a formula for converting (font size, padding, view size) pixels to sp or dp , for all devices, so that the aspect ratio remains the same? Using values for the folder values , values-sw360dp , values-sw600dp , values-sw720dp . Previously, I always set these values ​​by testing (that is, by eye). Now I thought, maybe they can all be counted?

Answer:

The following formulas work for me:

The sought value horizontally in dp = (Value in the layout horizontally in px * (Width of the device in px / Width of the layout in px)) / pixel density index

The required value vertically in dp = (Value in the layout vertically in px * (Height of the device in px / Height of the layout in px)) / pixel density index

Пример: 
Макет = 1080x1920 
Высота искомой view внутри макета равна 100px
Необходимо найти значение в dp для устройства Nexus S

Решение:
Используем вторую формулу.
Искомое значение = (100 * (800 / 1920)) / 1.5) = ~27.78dp
Scroll to Top