如何相互转换DP,PX,SP,尤其是DP和SP? [英] How to convert DP, PX, SP among each other, especially DP and SP?

查看:100
本文介绍了如何相互转换DP,PX,SP,尤其是DP和SP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 DP SP PX 之间的区别.在搜索了这个主题之后,我发现没有什么令我完全满意.也许这篇文章是重复的,但我仍然想知道从 DP 转换为 PX ,从 DP 转换为 SP ,从 SP PX ,从 PX SP ,从 SP DP ,从 DP SP ?我知道一些代码可以做到这一点,但是它们并不完美.

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.

推荐答案

DP到PX:

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

SP到PX:

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

DP到SP:

public static int dpToSp(float dp, Context context) {
    return (int) (dpToPx(dp, context) / context.getResources().getDisplayMetrics().scaledDensity);
}

这篇关于如何相互转换DP,PX,SP,尤其是DP和SP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆