[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Draw and move line segments snapping to a grid in C#

Draw and move line segments snapping to a grid

See the example Draw and move line segments in C# for basic information about the program. This example does the same thing, but lets you snap segments and end points to a grid.

When the drawing PictureBox is resized or when the "Snap To Grid" checkbox is checked or unchecked, the program calls the MakeBackgroundGrid method shown in the following code.

private void MakeBackgroundGrid() { if (!chkSnapToGrid.Checked) { picCanvas.BackgroundImage = null; } else { Bitmap bm = new Bitmap( picCanvas.ClientSize.Width, picCanvas.ClientSize.Height); for (int x = 0; x < picCanvas.ClientSize.Width; x += grid_gap) { for (int y = 0; y < picCanvas.ClientSize.Height; y += grid_gap) { bm.SetPixel(x, y, Color.Black); } } picCanvas.BackgroundImage = bm; } }

If the checkbox is not checked, this method sets the picCanvas control's background to null. Otherwise it makes a bitmap to fit the PictureBox, draws dots on it to show the grid, and sets the PictureBox's BackgroundImage property to the bitmap.

The other change to the program is how it handles new points. Whenever the program is about to do something with a point, it calls the following SnapToGrid method to snap that point's coordinates to the grid (if appropriate).

// Snap to the nearest grid point. private void SnapToGrid(ref int x, ref int y) { if (!chkSnapToGrid.Checked) return; x = grid_gap * (int)Math.Round((double)x / grid_gap); y = grid_gap * (int)Math.Round((double)y / grid_gap); }

This method rounds its x and y parameters to the nearest multiples of the grid's size.

The following code shows an example of how the program uses the SnapToGrid method. This event handler executes when the user is moving a segment's end point.

// We're moving an end point. private void picCanvas_MouseMove_MovingEndPoint( object sender, MouseEventArgs e) { // Move the point to its new location. int x = e.X + OffsetX; int y = e.Y + OffsetY; SnapToGrid(ref x, ref y); if (MovingStartEndPoint) Pt1[MovingSegment] = new Point(x, y); else Pt2[MovingSegment] = new Point(x, y); // Redraw. picCanvas.Invalidate(); }

The code gets the mouse's X and Y coordinates and calls SnapToGrid to snap to the nearest grid location. It then updates the appropriate segment end point (start point or end point) and redraws the PictureBox.

See the previous example for more details.

Download the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.