SilentKnight - 1 year ago 83

Android Question

I have known the difference among **DP**, **SP** and **PX**. And after searching this topic, I found nothing satisfying me completely. Maybe this post is a duplicate, but I still want to know what is the formula of converting from **DP** to **PX**, and **DP** to **SP**, from **SP** to **PX**, from **PX** to **SP**, from **SP** to **DP**, from **DP** to **SP**? I have known some codes to do this, but they are imperfect.

Answer

**DP to PX:**

```
public static int convertDpToPixels(float dp, Context context) {
int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics());
return px;
}
```

**SP to PX:**

```
public static int convertSpToPixels(float sp, Context context) {
int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, context.getResources().getDisplayMetrics());
return px;
}
```

**DP to SP:** (why would you need it?)

```
public static int convertDpToSp(float dp, Context context) {
int sp = (int) (convertDpToPixels(dp, context) / (float) convertSpToPixels(dp, context));
return sp;
}
```

Please correct me if I'm wrong in the last one, made it up just now.

Source (Stackoverflow)