安卓将dp单位转换为像素单位,系数为0.5f



我在这里读到关于将dp单位转换为像素单位的信息。但我无法理解 0.5f。这个数字从何而来,有什么用?

// The gesture threshold expressed in dp
private static final float GESTURE_THRESHOLD_DP = 16.0f;
// Get the screen's density scale
final float scale = getResources().getDisplayMetrics().density;
// Convert the dps to pixels, based on density scale
mGestureThreshold = (int) (GESTURE_THRESHOLD_DP * scale + 0.5f);
// Use mGestureThreshold as a distance in pixels...

将浮点数转换为整数将使它们下限。 0.5f 是将数字四舍五入:

x = (int) 3.9
print x // 3

x = (int) 3.9 + 0.5f
print x // 4

它用来圆润事物。 小数位数可以是小数(如 1.5(。 这意味着产品可能不是整数。 添加 .5 然后转换为 int 可确保如果数字在两个整数之间超过一半,则数字向上舍入,如果小于一半,则向下舍入。

最新更新