How to draw a rectangle in C# using a mouse

陌路散爱 提交于 2021-02-10 18:00:42

问题


I want to draw a rectangle on a form in C#. I read and found this article. Are there any samples or tutorials available ? The article was not very helpful.


回答1:


The article you linked appears to be C++, which may explain why it didn't help you much.

If you create events for MouseDown and MouseUp, you should have the two corner points you need for a rectangle. From there, it's a matter of drawing on the form. System.Drawing.* should probably be your first stop. There are a couple of tutorials linked below:

Drawing with Graphics in WinForms using C#

Draw a rectangle using Winforms (StackOverflow)

Graphics Programming using C#




回答2:


You need this 3 functions and variables:

    private Graphics g;
    Pen pen = new System.Drawing.Pen(Color.Blue, 2F);
    private Rectangle rectangle;
    private int posX, posY, width, height; 

Second you need to make a mouse down event:

    private void pictureCrop_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            posX = e.X;
            posY = e.Y;
        }
    }

Third, you need to implemente the mouse up event:

    private void pictureCrop_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button != MouseButtons.Left)
            return;

        if (e.X > posX && e.Y > posY) // top left to bottom right
        {
            width = Math.Abs(e.X - posX);
            height = Math.Abs(e.Y - posY);
        }
        else if (e.X < posX && e.Y < posY) // bottom right to top left
        {
            width = Math.Abs(posX - e.X);
            height = Math.Abs(posY - e.Y);

            posX = e.X;
            posY = e.Y;
        }
        else if (e.X < posX && e.Y > posY) // top right to bottom left
        {
            width = Math.Abs(posX - e.X);
            height = Math.Abs(posY - e.Y);

            posX = e.X;
        }
        else if (e.X > posX && e.Y < posY) // bottom left to top right
        {
            width = Math.Abs(posX - e.X);
            height = Math.Abs(posY - e.Y);

            posY = e.Y;
        }

        g.DrawImage(_bitmap, 0, 0);
        rectangle = new Rectangle(posX, posY, width, height);
        g = pictureCrop.CreateGraphics();
        g.DrawRectangle(pen, rectangle);
    }

And to ensure that when you resize or move the form the rectangle will be there:

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        Graphics graph = e.Graphics;
        graph.DrawImage(_bitmap, 0, 0);
        Rectangle rec = new Rectangle(posX, posY, width, height);
        graph.DrawRectangle(pen, rec);
    }


来源:https://stackoverflow.com/questions/3149803/how-to-draw-a-rectangle-in-c-sharp-using-a-mouse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!