I am trying to create some snap to grid functionality to be used at run time but I am having problems with the snapping part. I have successfully drawn a dotted grid on a panel but when I add a label control to the panel how to I snap the top, left corner of the label to the nearest dot?
Thanks
I don't think the accepted answer is correct. Here is why:
if the gridwidth = 3, the a point on x like 4 should map to 3 but x=5 should map to 6. using Pedery's answer they will both map to 3.
For correct result you need to round off like this (you can use float if points are fractions):
//Lets say.
int gridCubeWidth = 3;
int gridCubeHeight = 3;
int newX = Math.Round(oldX / gridCubeWidth) * gridCubeWidth;
int newY = Math.Round(oldY / gridCubeHeight) * gridCubeHeight;
pos.x - pos.x % gridWidth
should do it.
This one works better for me as it moves the point depending on how close it is to next or previous gird-point:
if (pt.X % gridWidth < gridWidth/2)
pt.X = pt.X - pt.X % gridWidth;
else
pt.X = pt.X + (gridWidth - pt.X % gridWidth);
if (pt.Y % gridHeight < gridHeight / 2)
pt.Y = pt.Y - pt.Y % gridHeight;
else
pt.Y = pt.Y + (gridHeight - pt.Y % gridHeight);
Here is a solution that rounds to the nearest grid point:
public static readonly Size Grid = new Size( 16, 16 );
public static readonly Size HalfGrid = new Size( Grid.Width/2, Grid.Height/2 );
// ~~~~ Round to nearest Grid point ~~~~
public Point SnapCalculate( Point p )
{
int snapX = ( ( p.X + HalfGrid.Width ) / Grid.Width ) * Grid.Width;
int snapY = ( ( p.Y + HalfGrid.Height ) / Grid.Height ) * Grid.Height;
return new Point( snapX, snapY );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With