Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Create Snap To Grid Functionality

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

like image 863
Nathan Avatar asked Dec 12 '09 05:12

Nathan


4 Answers

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;
like image 188
numan salati Avatar answered Nov 16 '22 15:11

numan salati


pos.x - pos.x % gridWidth should do it.

like image 43
Pedery Avatar answered Nov 16 '22 15:11

Pedery


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);
like image 5
silverspoon Avatar answered Nov 16 '22 15:11

silverspoon


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 );
    }
like image 4
Roland Avatar answered Nov 16 '22 15:11

Roland