简体   繁体   中英

C# Draw on PictureBox with Graphics.DrawLine() not working on Paint event

I have a from with a PictureBox and a button (see image). 在此处输入图片说明

When user click on "Draw" the programm draws two crosses.

I did the same thing for the PictureBox Paint event handler, but if I minimize the form and reopen it nothing is drawn (except Image property of picture box): 在此处输入图片说明

Code:

 public partial class Form1 : Form
{

    Point[] points = new Point[2];
    Graphics g;
    public Form1()
    {
        InitializeComponent();
        points[0] = new Point(50, 50);
        points[1] = new Point(100, 100);
        g = pictureBox1.CreateGraphics();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        DrawCrosses(points);
    }

    private void DrawCrosses(Point[] points)
    {
        
        Pen pen = new Pen(Color.Red)
        {
            Width = 2
        };
        foreach (Point p in points)
        {
            Point pt1 = new Point(p.X, p.Y - 10);
            Point pt2 = new Point(p.X, p.Y + 10);
            Point pt3 = new Point(p.X - 10, p.Y);
            Point pt4 = new Point(p.X + 10, p.Y);
            g.DrawLine(pen, pt1, pt2);
            g.DrawLine(pen, pt3, pt4);
        }
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        DrawCrosses(points);
    }
}

You should not create a new Graphics object in the event handler.

You should use the one passed from event

public partial class Form1 : Form
{
    Point[] points = new Point[2];
    public Form1()
    {
        InitializeComponent();
        points[0] = new Point(50, 50);
        points[1] = new Point(100, 100);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        DrawCrosses(points, pictureBox1.CreateGraphics());
    }

    private void DrawCrosses(Point[] points, Graphics g)
    {

        Pen pen = new Pen(Color.Red)
        {
            Width = 2
        };
        foreach (Point p in points)
        {
            Point pt1 = new Point(p.X, p.Y - 10);
            Point pt2 = new Point(p.X, p.Y + 10);
            Point pt3 = new Point(p.X - 10, p.Y);
            Point pt4 = new Point(p.X + 10, p.Y);
            g.DrawLine(pen, pt1, pt2);
            g.DrawLine(pen, pt3, pt4);
        }
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        DrawCrosses(points, e.Graphics);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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