绘制矩形的所有方向

本文关键字:方向 绘制 | 更新日期: 2023-09-27 18:16:47

我需要用鼠标移动在picturebox内部画一个矩形。不超过图片框的边框。

向右或向下拖动对我来说很好…如何使运动反向?

我的代码如下。

    Rectangle Rect = new Rectangle();
    private Point RectStartPoint;
    public Pen cropPen = new Pen(Color.Red, 2);
    public Form1()
    {
        InitializeComponent();
    }
    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        RectStartPoint = e.Location;
        picImagem.Invalidate();
    }
    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            Point tempEndPoint = e.Location;
            Rect.Location = new Point(Math.Min(RectStartPoint.X, tempEndPoint.X),
                Math.Min(RectStartPoint.Y, tempEndPoint.Y));
            Rect = new Rectangle(
                Math.Min(tempEndPoint.X, Rect.Left),
                Math.Min(tempEndPoint.Y, Rect.Top),
                Math.Min(e.X - RectStartPoint.X, picImagem.ClientRectangle.Width - RectStartPoint.X),
                Math.Min(e.Y - RectStartPoint.Y, picImagem.ClientRectangle.Height - RectStartPoint.Y));
            picImagem.Refresh();
            picImagem.CreateGraphics().DrawRectangle(cropPen, Rect);
        }
    }

绘制矩形的所有方向

您可以这样修改鼠标移动代码:

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == System.Windows.Forms.MouseButtons.Left)
    {
        Point tempEndPoint = e.Location;
        var point1 = new Point(
            Math.Max(0, Math.Min(RectStartPoint.X, tempEndPoint.X)),
            Math.Max(0, Math.Min(RectStartPoint.Y, tempEndPoint.Y)));
        var point2 = new Point(
            Math.Min(this.picImagem.Width, Math.Max(RectStartPoint.X, tempEndPoint.X)),
            Math.Min(this.picImagem.Height, Math.Max(RectStartPoint.Y, tempEndPoint.Y)));

        Rect.Location = point1;
        Rect.Size = new Size(point2.X - point1.X, point2.Y - point1.Y);

        picImagem.Refresh();
        picImagem.CreateGraphics().DrawRectangle(cropPen, Rect);
    }
}

在上面的代码中,我们首先标准化矩形的开始和结束,使开始和结束都在矩形的边界内。然后画出来