我有一個帶有圖片框和按鈕的 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);
}
}
uj5u.com熱心網友回復:
您不應在事件處理程式中創建新的 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);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/318259.html
