将绘制的矩形对齐到网格

本文关键字:对齐 网格 绘制 | 更新日期: 2023-09-27 18:09:39

我有一个鼠标拖动矩形的脚本,还有一个网格绘制脚本,它在图片框上绘制一个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);
    }
}

将绘制的矩形对齐到网格

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

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());

你可以在鼠标移动中像这样调整宽度:

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