2013-06-29 131 views

回答

0

下面是一個將每個「形狀」作爲GraphicsPath存儲在類級別List中的快速示例。每個路徑都使用窗體的Paint()事件中提供的Graphics繪製。隨機矩形添加到列表<>與每個按鈕的點擊和刷新()被調用針對的形式,迫使它重新繪製本身:

public partial class Form1 : Form 
{ 

    public Form1() 
    { 
     InitializeComponent(); 
     this.Paint += new PaintEventHandler(Form1_Paint); 
    } 

    private Random R = new Random(); 
    private List<System.Drawing.Drawing2D.GraphicsPath> Paths = new List<System.Drawing.Drawing2D.GraphicsPath>(); 

    private void button1_Click(object sender, EventArgs e) 
    { 
     Point pt1 = new Point(R.Next(this.Width), R.Next(this.Height)); 
     Point pt2 = new Point(R.Next(this.Width), R.Next(this.Height)); 

     System.Drawing.Drawing2D.GraphicsPath shape = new System.Drawing.Drawing2D.GraphicsPath(); 
     shape.AddRectangle(new Rectangle(new Point(Math.Min(pt1.X,pt2.X), Math.Min(pt1.Y, pt2.Y)), new Size(Math.Abs(pt2.X - pt1.X), Math.Abs(pt2.Y - pt1.Y)))); 
     Paths.Add(shape); 

     this.Refresh(); 
    } 

    private void Form1_Paint(object sender, PaintEventArgs e) 
    { 
     Graphics G = e.Graphics; 
     foreach (System.Drawing.Drawing2D.GraphicsPath Path in Paths) 
     { 
      G.DrawPath(Pens.Black, Path); 
     } 
    } 

} 
0

爲了提高甚至用手閱讀本SO後的塗料(基本調用invalidate()方法)

SO post: How do I call paint event?

然而,你可能需要有某種形式的內部「drawshape」標誌,設置/清除按鈕點擊查看您的油漆,甚至處理方法中。這個標誌將會調用你的繪畫事件處理程序來繼續繪製你的形狀或者根本不繪製你的形狀(每次調用表單繪製時)