C# 在 PictureBox 上绘制 Graphics.DrawLine() 不适用于 Paint 事件

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

我有一个带有 PictureBox 和一个按钮的 from(见图)。

当用户点击“绘制”时,程序会绘制两个十字。

我对 PictureBox Paint 事件处理程序做了同样的事情,但是如果我最小化表单并重新打开它,则不会绘制任何内容(图片框的图像 属性 除外):

代码:

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

您不应在事件处理程序中创建新的 Graphics 对象。

你应该使用事件传递的那个

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