如题,上代码即可:
public class UIUtils {
private static float scale = -1;
/**
* transform dip to pixl
*/
public static int dipToPx(Context context, float dpValue) {
if (scale == -1) {
scale = context.getResources().getDisplayMetrics().density;
}
return (int) (dpValue * scale + 0.5f);
}
/**
* transform pixl to dip
*/
public static int pxToDip(Context context, float pxValue) {
if (scale == -1) {
scale = context.getResources().getDisplayMetrics().density;
}
return (int) (pxValue / scale + 0.5);
}
}
本文介绍了一个用于Android开发中尺寸单位转换的工具类UIUtils。该类提供了两个静态方法,用于实现dp(密度无关像素)到px(像素)及px到dp之间的相互转换。这些方法考虑了不同设备屏幕密度的差异,有助于实现跨设备尺寸的一致性。
1万+

被折叠的 条评论
为什么被折叠?



