Android-使用0.5f系数将dp单位转换为像素单位

3

我在这里读到了有关将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...
3个回答

3
将浮点数转换为整数会向下取整。0.5f是用来四舍五入的数字:
x = (int) 3.9
print x // 3



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

2

这是为了让数字变得更加整齐。比如说,缩放因子可能是一个小数(比如1.5)。这意味着计算结果可能不是整数。加上0.5然后转换成整数可以保证在值恰好处于两个整数之间时向上取整,而在值偏离两个整数之间时向下取整。


0
所有答案都是正确的,你也可以选择使用。
Math.round((float) dp * scale);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接