简体   繁体   English

如何在PictureBox C#中绘制对象?

[英]How to draw object in PictureBox c#?

I trying draw a rectangles in PictureBox by mouse click: 我试图通过单击鼠标在PictureBox中绘制一个矩形:

    private void MyPictureBoxMouseClick(object sender, MouseEventArgs e)
    {
        using (Graphics g = MyPictureBox.CreateGraphics())
        {
            var pen = new Pen(Color.Black, 2);
            g.DrawRectangle(pen, e.X, e.Y, 50, 50);

            pen.Dispose();
        }
    }

And rectangles are drawning. 并绘制矩形。 But when i move mouse beyond the PictureBox all rectangles are disappear. 但是,当我将鼠标移到PictureBox之外时,所有矩形都消失了。 How to avoid it? 如何避免呢?

UPDATE 更新
I added a Paint event: 我添加了一个Paint事件:

  private List<Rectangle> Rectangles { set; get; }
        private void MyPictureBoxPaint(object sender, PaintEventArgs e)
    {
        using (Graphics g = MyPictureBox.CreateGraphics())
        {
            var pen = new Pen(Color.Black, 2);
            foreach (var rect in Rectangles)
            {
                g.DrawRectangle(pen, rect); 
            }

             pen.Dispose();
        }
    }

    private void MyPictureBoxMouseClick(object sender, MouseEventArgs e)
    {
        Rectangles.Add(new Rectangle(e.X, e.Y, 50, 50));
        MyPictureBox.Refresh();
    }

But now rectangles not drawning. 但是现在不绘制矩形。

Update 更新资料

Oh it was my mistake. 哦,那是我的错。

g.DrawRectangle(pen, rect);  -> e.Graphics.DrawRectangle(pen, rect); 

Yes, you're drawing over the picture box. 是的,您正在绘制图片框。 When the next paint messgae arrives, picturebox re-paints itself again at that time it'll overwrite your rectangles. 当下一个绘制消息到达时,Picturebox会在那时再次重新绘制自身,它将覆盖您的矩形。

You either need to draw it in Paint event in order to make your rectangles survive or you can Draw over the PictureBox.Image so it will stay there. 您可能需要在Paint事件中绘制它以便使矩形保留下来,或者可以在PictureBox.Image绘制以便将其保留在那里。

For your edit: You need to use e.Graphics property. 为了进行编辑:您需要使用e.Graphics属性。 For instance following code works for me. 例如下面的代码对我有用。

private void MyPictureBoxPaint(object sender, PaintEventArgs e)
{
    Graphics g = e.Graphics;
    using (var pen = new Pen(Color.Black, 2))
    {
        foreach (var rect in Rectangles)
        {
            g.DrawRectangle(pen, rect);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM