android 尺寸转换工具,Android工具类系列-DensityUtil(尺寸单位转换)

丁文轩
2023-12-01

这个工具类用于尺寸转换,相信你们都了解。主要是:dp2px, px2dp, sp2px, px2sp。android

package org.yxm.android.utils;

import android.content.Context;

import android.util.TypedValue;

/**

* Created by yxm on 16-6-23.

*/

public class DensityUtil {

private DensityUtil() {

throw new UnsupportedOperationException("cannot be instantiated");

}

/**

* dp转px

*/

public static int dp2px(Context context, float dpVal) {

return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,

dpVal, context.getResources().getDisplayMetrics());

}

/**

* sp转px

*/

public static int sp2px(Context context, float spVal) {

return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,

spVal, context.getResources().getDisplayMetrics());

}

/**

* px转dp

*/

public static float px2dp(Context context, float pxVal) {

final float scale = context.getResources().getDisplayMetrics().density;

return (pxVal / scale);

}

/**

* px转sp

*/

public static float px2sp(Context context, float pxVal) {

return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);

}

}

 类似资料: