簡體   English   中英

C# 使用 Graphics.DrawLine() 在 PictureBox 上繪制不適用於 Paint 事件

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

我有一個帶有圖片框和按鈕的 from(見圖)。 在此處輸入圖片說明

當用戶單擊“繪制”時,程序會繪制兩個十字。

我對 PictureBox Paint 事件處理程序做了同樣的事情,但如果我最小化窗體並重新打開它,則不會繪制任何內容(圖片框的 Image 屬性除外): 在此處輸入圖片說明

代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM