4

What is the sp value for 40px? Please also tell the formula of conversion.

I am trying to convert my font sizes present in psd into sp units for mdpi density i.e. 320*480 with 160 dpi

Ayaz Alavi
  • 4,825
  • 8
  • 50
  • 68

2 Answers2

14
case COMPLEX_UNIT_SP:
     return value * metrics.scaledDensity;

from the TypedValue.applyDimension() source

This converts sp to px, just transpose it and you get the formula for converting px to sp:

sp = px / DisplayMetrics.scaledDensity
2
px = dp * (dpi / 160)

This doesn't convert your sp to px or vice versa. But, sp and dp are almost similar, and hence, I think it's safe to use this formula.

Density-independent pixel (dp) A virtual pixel unit that you should use when defining UI layout, to express layout dimensions or position in a density-independent way.

The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, which is the baseline density assumed by the system for a "medium" density screen. At runtime, the system transparently handles any scaling of the dp units, as necessary, based on the actual density of the screen in use. The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels. You should always use dp units when defining your application's UI, to ensure proper display of your UI on screens with different densities.

Source: Supporting Multiple Screens.

Ghost
  • 3,966
  • 1
  • 25
  • 36