Search code examples
androidandroid-layout

Android-Convert dp units to pixel units with factor 0.5f


I read here about converting dp units to pixel units. But I cant understand the 0.5f. Where does this number come from and what is the use of it?

// 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...

Solution

  • Its to round things. Scale may be a decimal (like 1.5). This means the product may not be a whole number. Adding .5 then converting to int ensures that the number rounds up if the number is more than halfway between two integers, and down if its less than halfway.