Android中,单位dp、sp、px互相转换工具类
16lz
2021-01-26
可以定义一个工具类,用来获取系统的转化比值,然后需要使用时调用即可。具体代码如下:
/** * dp、sp转化工具 * * @author h55l5 * */public class DisplayUtil { /** * 将px转化为dip,保证尺寸大小不变 * * @param context * @param pxValue * @return dp值 */ public static int px2dip(Context context, float pxValue) { return (int) (pxValue / getScale(context) + 0.5f); } /** * 将dip值转化为对应的px值 * * @param context * @param dipValue * @return px值 */ public static int dip2px(Context context, float dipValue) { return (int) (dipValue * getScale(context) + 0.5f); } /** * 将对应的px值转化为sp值 * * @param context * @param pxValue * @return 转化后的sp值 */ public static int px2sp(Context context, float pxValue) { return (int) (pxValue / getFontScale(context) + 0.5f); } /** * 将对应的sp值转化为px值 * * @param context * @param spValue * @return 转化好的px值 */ public static int sp2px(Context context, float spValue) { return (int) (spValue * getFontScale(context) + 0.5f); } /** * 获取系统的转化比例 * * @param context * @return */ private static float getScale(Context context) { return context.getResources().getDisplayMetrics().density; } /** * 获取系统的转化比例 * * @param context * @return */ private static float getFontScale(Context context) { return context.getResources().getDisplayMetrics().scaledDensity; }}
还可以通过系统的方法来进行相关的转化,具体代码如下:
public class DisplayUtil { public static int dp2px(Context context, int dp) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics()); } public static int sp2px(Context context, int sp) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, context.getResources().getDisplayMetrics()); }}
更多相关文章
- android Notification 的使用!!!
- Android(安卓)Tint使用
- Android——常用的系统服务
- Android(安卓)系统剪贴板的使用 - 复制、获取和清空
- Android系统架构介绍
- 【Tech-Android-View】Android中可以使用的网络音乐资源(榜单 歌
- 安卓模拟器Android(安卓)SDK Manager 无法获取SDK列表的解决办法
- Android使用criteria选择合适的地理位置服务实现方法
- Android(安卓)系统提供媒体库 URI 与 数据库的对应关系