将绘制的矩形捕捉到网格

时间:2014-06-20 17:39:11

标签: c# winforms grid picturebox

我有下面的鼠标拖动绘制一个矩形,还有一个网格绘图脚本,在图片框上绘制一个32x32网格,我试图做的是将矩形捕捉到网格,然后在屏幕内拍摄矩形。

我已经获得了屏幕截图和矩形的绘图,而不是捕捉网格位的工作。

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 &&
        _selecting &&
        _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 < numOfCells; ++y)
    {
        g.DrawLine(p, 0, y * ysize, numOfCells * ysize, y * ysize);
    }

    for (int x = 0; x < numOfCells; ++x)
    {
        g.DrawLine(p, x * xsize, 0, x * xsize, numOfCells * xsize);
    }
}

1 个答案:

答案 0 :(得分:2)

首先我要声明一个捕捉方法

private Point SnapToGrid(Point p)
{
    double x = Math.Round((double)p.X / xsize) * xsize;
    double y = Math.Round((double)p.Y / ysize) * ysize;
    return new Point((int)x, (int)y);
}

然后你可以在MouseDown中初始化这样的选择:

_selection = new Rectangle(SnapToGrid(e.Location), new Size());

你可以在MouseMove中调整宽度,如下所示:

Point dest = SnapToGrid(e.Location);
_selection.Width = dest.X - _selection.X;
_selection.Height = dest.Y - _selection.Y;