title: Snap drawn rectangle to grid
body: <p>I have the below which draws a rectangle on mouse drag and also a grid drawing script which draws a 32x32 grid on the picture box what I'm trying to do is snap the rectangle to the grid then screen shot inside the rectangle.</p>
  
  <p>I've got the screen shot bit and the drawing of the rectangle just not the snapping to grid bit working.</p>
  
  <pre><code>private bool _selecting;
  private Rectangle _selection;
  
  private void picCanvas_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
  {
      if (e.Button == MouseButtons.Left)
      {
          _selecting = true;
          _selection = new Rectangle(new Point(e.X, e.Y), new Size());
      }
  }
  
  private void picCanvas_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
  {
      if (_selecting)
      {
          _selection.Width = e.X - _selection.X;
          _selection.Height = e.Y - _selection.Y;
  
          pictureBox1.Refresh();
      }
  }
  
  public Image Crop(Image image, Rectangle selection)
  {
      Bitmap bmp = image as Bitmap;
  
      // Check if it is a bitmap:
      if (bmp == null)
          throw new ArgumentException("No valid bitmap");
  
      // Crop the image:
      Bitmap cropBmp = bmp.Clone(selection, bmp.PixelFormat);
  
      // Release the resources:
      image.Dispose();
  
      return cropBmp;
  }
  
  private void picCanvas_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
  {
      if (e.Button == MouseButtons.Left &amp;&amp;
          _selecting &amp;&amp;
          _selection.Size != new Size())
      {
          // Create cropped image:
          //Image img = Crop(pictureBox1.Image, _selection);
  
          // Fit image to the picturebox:
          //pictureBox1.Image = img;
  
          _selecting = false;
      }
      else
          _selecting = false;
  }
  
  private void pictureBox1_Paint(object sender, PaintEventArgs e)
  {
      if (_selecting)
      {
          // Draw a rectangle displaying the current selection
          Pen pen = Pens.GreenYellow;
          e.Graphics.DrawRectangle(pen, _selection);
      }
  
      Graphics g = e.Graphics;
      int numOfCells = amount;
      Pen p = new Pen(Color.LightGray);
  
      for (int y = 0; y &lt; numOfCells; ++y)
      {
          g.DrawLine(p, 0, y * ysize, numOfCells * ysize, y * ysize);
      }
  
      for (int x = 0; x &lt; numOfCells; ++x)
      {
          g.DrawLine(p, x * xsize, 0, x * xsize, numOfCells * xsize);
      }
  }
  </code></pre>