简体   繁体   English

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

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

I have a from with a PictureBox and a button (see image).我有一个带有图片框和按钮的 from(见图)。 在此处输入图片说明

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):我对 PictureBox Paint 事件处理程序做了同样的事情,但如果我最小化窗体并重新打开它,则不会绘制任何内容(图片框的 Image 属性除外): 在此处输入图片说明

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.您不应在事件处理程序中创建新的 Graphics 对象。

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

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

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