|
package com.jingewenku.abrahamcaijin.commonutil; | |
| import android.content.Context; |
| import android.util.TypedValue; |
| |
| /** |
| * @Description:主要功能:常用单位转换的辅助类 |
| * @Prject: CommonUtilLibrary |
| * @Package: com.jingewenku.abrahamcaijin.commonutil |
| * @author: AbrahamCaiJin |
| * @date: 2017年05月16日 15:29 |
| * @Copyright: 个人版权所有 |
| * @Company: |
| * @version: 1.0.0 |
| */ |
| |
| public class DensityUtils { |
| |
| private DensityUtils() { |
| throw new UnsupportedOperationException("cannot be instantiated"); |
| } |
| |
| /** |
| * 根据手机的分辨率从 dip 的单位 转成为 px(像素) |
| */ |
| public static int dip2px(Context context, float dpValue) { |
| final float scale = context.getResources().getDisplayMetrics().density; |
| return (int) (dpValue * scale + 0.5f); |
| } |
| |
| /** |
| * 根据手机的分辨率从 px(像素) 的单位 转成为 dp |
| */ |
| public static int px2dip(Context context, float pxValue) { |
| final float scale = context.getResources().getDisplayMetrics().density; |
| return (int) (pxValue / scale + 0.5f); |
| } |
| /** |
| * dp转px |
| * |
| * @param context |
| * @param dpVal |
| * @return |
| */ |
| public static int dp2px(Context context, float dpVal) |
| { |
| return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, |
| dpVal, context.getResources().getDisplayMetrics()); |
| } |
| |
| /** |
| * sp转px |
| * |
| * @param context |
| * @param spVal |
| * @return |
| */ |
| public static int sp2px(Context context, float spVal) |
| { |
| return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, |
| spVal, context.getResources().getDisplayMetrics()); |
| } |
| |
| /** |
| * px转dp |
| * |
| * @param context |
| * @param pxVal |
| * @return |
| */ |
| public static float px2dp(Context context, float pxVal) |
| { |
| final float scale = context.getResources().getDisplayMetrics().density; |
| return (pxVal / scale); |
| } |
| |
| /** |
| * px转sp |
| * |
| * @param pxVal |
| * @param pxVal |
| * @return |
| */ |
| public static float px2sp(Context context, float pxVal) |
| { |
| return (pxVal / context.getResources().getDisplayMetrics().scaledDensity); |
| } |
| |
| } |