开发者

How to draw a rectangle in C# using a mouse

I want to draw a rectangle on a form in C#. I read and found this article. Are there any samples or tutorials a开发者_高级运维vailable ? The article was not very helpful.


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#


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜