向所有方向绘制矩形

时间:2015-10-07 16:05:23

标签: c# winforms gdi+

我需要在带有mousemove的图片框内画一个矩形。 没有超出边框的图片框。

向右或向下拖动对我来说很好......如何使动画反转?

我的代码如下。

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

        }
    }

1 个答案:

答案 0 :(得分:0)

您可以通过以下方式更正鼠标移动代码:

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

    }
}

在上面的代码中,我们首先规范化矩形的开始和结束,并使矩形的边界开始和结束。然后我们画它。