2016-05-14 79 views
-1

我有一個面板和一個按鈕。即:如何通過點擊按鈕在面板上繪製東西

private void button1_Click(object sender, EventArgs e) 
    { 
     panel2.Paint += new PaintEventHandler(panel2_Paint); 
     panel2.Refresh(); 
    } 

和:

private void panel2_Paint(object sender, PaintEventArgs e) 
    { 


      Graphics g = this.CreateGraphics(); 
      Graphics[,] g1 = new Graphics[140, 140]; 
      int[,] graph = new int[140, 140]; 

      int i, j; 
      for (i = 0; i < 140; i++) 
       for (j = 0; j < 140; j++) 
       { 
        graph[i, 8] = 1; 
        graph[i, 10] = 1; 
       } 

      Pen p = new Pen(Color.Blue); 
      SolidBrush mySolidColorBrush = new SolidBrush(Color.Blue); 
      Graphics a; 
      a = this.CreateGraphics(); 

      for (i = 1; i <= 10; i++) 
       for (j = 1; j <= 14; j++) 
       { 
        g.DrawEllipse(p, 80 * i, 80 * j, 10, 10); 
        g.FillEllipse(mySolidColorBrush, 80 * i, 80 * j, 20, 20); 
      a.DrawLine(Pens.Blue, 80 * i, 80 * j, 80 * (i - 1), 80 * (j - 1)); 
       } 

    } 

當我點擊按鈕的輸出應顯示面板上,但我的情況下,它會顯示在表格。

回答

-1

您應該創建自己的用戶控件來完成繪圖任務。

public partial class UserControl1 : UserControl 
{ 
    public UserControl1() 
    { 
     InitializeComponent(); 
    } 

    public void DrawStuff() 
    { 
     this.Paint += new PaintEventHandler(panel1_Paint); 
     this.Refresh(); 
    } 

    private void panel1_Paint(object sender, PaintEventArgs e) 
    { 


     Graphics g = e.Graphics; 
     Graphics[,] g1 = new Graphics[140, 140]; 
     int[,] graph = new int[140, 140]; 

     int i, j; 
     for (i = 0; i < 140; i++) 
      for (j = 0; j < 140; j++) 
      { 
       graph[i, 8] = 1; 
       graph[i, 10] = 1; 
      } 

     Pen p = new Pen(Color.Blue); 
     SolidBrush mySolidColorBrush = new SolidBrush(Color.Blue); 
     Graphics a; 
     a = this.CreateGraphics(); 

     for (i = 1; i <= 10; i++) 
      for (j = 1; j <= 14; j++) 
      { 
       g.DrawEllipse(p, 80 * i, 80 * j, 10, 10); 
       g.FillEllipse(mySolidColorBrush, 80 * i, 80 * j, 20, 20); 
       a.DrawLine(Pens.Blue, 80 * i, 80 * j, 80 * (i - 1), 80 * (j - 1)); 
      } 

    } 
} 

然後,你可以從父控件調用公共方法繪製東西。

private void button1_Click(object sender, EventArgs e) 
    { 
     userControl11.DrawStuff(); 
    } 

enter image description here

+0

這是你可以通過自己創建自定義控制。檢查視頻https://www.youtube.com/watch?v=l5L_q_jI494 –

+0

userControl11.DrawStuff(); 這裏usercontrol1不是一個對象,所以用這個 –

+0

來調用一個函數是無效的。你需要做的步驟是:1.創建一個新的UserControl(即UserControl1)2.將這兩個方法添加到新的控件中3.編譯你的解決方案4.將新UserControl1拖到您的UI中5.從Button –