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);
}
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;
}
}
}
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();
}
}
}
The complete source code for this post is at this GitHub commit.
No comments:
Post a Comment