android手机dp与px转换工具类

xiaoxiao2021-02-28  97

android手机dp与px转换工具类

public final class DensityUtil { private static float density = -1F; private static int widthPixels = -1; private static int heightPixels = -1; private DensityUtil() { } //获取屏幕密度(获得的不是真实的屏幕密度,而是相对于某个值的屏幕密度,应该是密度的一个比例) public static float getDensity() { if (density <= 0F) { density = x.app().getResources().getDisplayMetrics().density; } return density; } //dp转px,0.5f是因为强制转换成int时候要四舍五入 public static int dip2px(float dpValue) { return (int) (dpValue * getDensity() + 0.5F); } //px转dp,0.5f是因为强制转换成int时候要四舍五入 public static int px2dip(float pxValue) { return (int) (pxValue / getDensity() + 0.5F); } //获取屏幕宽度单位px(像素) public static int getScreenWidth() { if (widthPixels <= 0) { widthPixels = x.app().getResources().getDisplayMetrics().widthPixels; } return widthPixels; } //获取屏幕高度单位px(像素) public static int getScreenHeight() { if (heightPixels <= 0) { heightPixels = x.app().getResources().getDisplayMetrics().heightPixels; } return heightPixels; } }

转载请注明原文地址: https://www.6miu.com/read-36559.html

最新回复(0)