Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/261.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在PictureBox c#中绘制对象?_C#_Winforms_Picturebox - Fatal编程技术网

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

如何在PictureBox c#中绘制对象?,c#,winforms,picturebox,C#,Winforms,Picturebox,我尝试通过鼠标单击在PictureBox中绘制矩形: private void MyPictureBoxMouseClick(object sender, MouseEventArgs e) { using (Graphics g = MyPictureBox.CreateGraphics()) { var pen = new Pen(Color.Black, 2); g.DrawRectangle(

我尝试通过鼠标单击在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();
        }
    }
矩形正在绘制。但当我将鼠标移到PictureBox之外时,所有的矩形都消失了。如何避免呢

更新
我添加了一个绘画活动:

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

是的,你在画框上画画。当下一个绘制消息到达时,picturebox会重新绘制自己,此时它将覆盖您的矩形

您需要在
Paint
事件中绘制它,以使矩形保留下来,或者您可以在
PictureBox.Image
上绘制它,使其保持不变

对于您的编辑:您需要使用
e.Graphics
属性。例如,下面的代码适合我

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

你能更具体地描述消失的矩形吗?你需要将基本体存储在一个列表中,然后从列表中绘制到图片框中。当前,它们在下一次重新绘制picturebox时丢失。您是否尝试挂接到
Draw
事件?我认为你需要在那里做这件事;)当你编辑你的问题时,注意通过评论通知回答者,否则他们不会看到你的问题被更新。
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);
        }
    }
}