The idea is to make sure that the position of any object is limited to a specific set of numbers; those. the final position should be rounded and fall into this set.
The set consists of all factors for an arbitrary number, j ; j controls the strength of the "binding" and determines which numbers are displayed in the set. The new position, again, should consist only of the numbers that appear in the set.
For example, let's say that the initial position of the object is (5, 0) , and we want to move it to (16, 23) . Let it go ahead and give a snap 5 . This means that the position of the object can consist only of factors 5 . The starting position already falls into this set, but not in the new position.
To simulate a βsnapβ, the new position must fall on (15,20) or (20, 25) . Finding the closest odds of 16 and 23 will give you the correct point. In most cases, you need to round the result.
Example
//Get original point of object relative to container element var original_point = e.GetPosition(sender); //Calculate new x and y position based on mouse //var new_x = ... //var new_y = ... //New position must be multiple of 8 var snap = 8; //Get nearest factor of result position new_x = original_point.X.NearestFactor(snap); new_y = original_point.Y.NearestFactor(snap); public static double NearestFactor(this double Value, double Factor) { return Math.Round((Value / Factor), MidpointRounding.AwayFromZero) * Factor; }
It goes without saying that this algorithm can also be used when resizing an object to ensure both the position of the object and the size of the "snap".
source share