Simple Snap-To-Grid
So many people seem to struggle over this simple
functionality that I thought it would be a great idea to create a little base
class that shoehorns snap to grid behavior into the mouse handling methods and
events.
Essentially, snap-to-grid is a low-pass filter that removes
most of the mouse movements and only leaves the ones you're interested in.
There is however the right and a wrong way to do this filtering. The wrong
way, which is extremely simple, is to divide the mouse position by a certain
value and then multiply by that value again. If this is done using integer
method then the rounding of the divided integer will remove all the intermediate
values and leave you with the mouse position rounded down to the nearest desired
grid position. This is OK for quick and dirty work but of course, a
competent system would snap to the nearest grid rounding down until the position
got to halfway between the two points and then rounding up after it has passed
the halfway mark.
The code shown in this listing takes
a MouseEventArgs provided by the various mouse events and returns another
that has been snapped to a n adjustable grid of pixels.
This listing shows the entire
snap-to-grid class. You can use this class in two ways. Either as it's used
in the demo, as a stand-alone control and adding event-handlers where
appropriate or alternatively, you can derive from the class so that your
controls inherit grid-snapping abilities.
This listing shows code that tests it.
Figure 1 shows the code in action.

Figure 1. Pick a point...
You can find the Source Code files here.
Return to the main index.