Thursday, April 7, 2022

9-How to snap to grid

Now that the Test Diagram application has component move with mouse capability, it is advantangeous for an engineering application to have a snap to grid capability for easier drawing of wires and lines. Snap to grid means that when a component is moved, the location will always start on grid point such as 100,100. Let's add a new method to the TestDiagramMainForm code called SnapToGrid():

private void SnapToGrid(ref int x, ref int y)
{
    x = grid_gap * (int)Math.Round((double)x / grid_gap);
    y = grid_gap * (int)Math.Round((double)y / grid_gap);
}

The method arguments are the current x,y location which can be anywhere. The x,y values are then "snapped" to the grid using the Math.Round() method to find the nearent grid point. Note that the values are returned to the calling program using pass by reference arguments rather than pass by value. This is how to return more than one value from a function in C#.

Next we modify the Mouse Down event to support snap to grid as follows:

private void schematicCanvas_MouseDown(object sender, MouseEventArgs e)
{
    isMouseDown = true;
 
    // Snap the start point to the Grid
    int x = e.X;
    int y = e.Y;
    SnapToGrid(ref x, ref y);
    NewPt1.X = x;
    NewPt1.Y = y;
 
    // Iterate over the component list and test each to see if it is "hit"
    foreach (Comp comp in comps)
    {
        if (hitTest(comp))
        {
            tempComp = comp;
            offset.X = NewPt1.X - comp.loc.X;
            offset.Y = NewPt1.Y - comp.loc.Y;
        }
    }
}

This modification snaps the mouse x,y point to the nearest grid point before setting the new component location.

A similar modification is needed in the Mouse Move event code:

private void schematicCanvas_MouseMove(object sender, MouseEventArgs e)
{
    if (isMouseDown == true)
    {
        if (tempComp != null)
        {
            int x = e.X;
            int y = e.Y;
            SnapToGrid(ref x, ref y);
            tempComp.loc = new Point(x - offset.X, y - offset.Y);
            schematicCanvas.Invalidate();
        }
    }
}

Run the program, add a rectangle component, move the component with the mouse and ensure that its position is "snapped" to a grid point.

The complete source code for this post is at this GitHub commit.

No comments:

Post a Comment

34-Microwave Tools with Analysis (Series Final Post)

In this final blog post, I have integrated Y-Matrix analysis into the Microwave Tools project. This version has addition Lumped, Ideal, Micr...