前言
根据手机分辨率从 dp 的单位转成为 px(像素)。
代码
工具类 :
public class Utils {
// 根据手机的分辨率从 dp 的单位 转成为 px(像素)
public static int dip2px(Context context, float dpValue) {
// 获取当前手机的像素密度(1个dp对应几个px)
float scale = context.getResources().getDisplayMetrics().density;
// 四舍五入取整
return (int) (dpValue * scale + 0.5f);
}
}
使用 :
Window window = this.getWindow();
// 设置dialog的布局样式 让其位于顶部
window.setGravity(Gravity.TOP | Gravity.RIGHT);
WindowManager.LayoutParams lp = window.getAttributes();
// 设置居于底部的距离
lp.x = Utils.dip2px(mContext, 10);
// 设置居于底部的距离
lp.y = Utils.dip2px(mContext, 10);
window.setAttributes(lp);
总结
以上就是根据手机分辨率从 dp 的单位转成为 px(像素)的内容。