2012-05-23 99 views
2

我正在嘗試僅將基本形狀繪製到窗體上的面板上。到目前爲止沒有任何反應,我不知道爲什麼。此方法在我的表單的構造函數中調用。面板中的圖形故障

private void doGraphics() 
    { 
     Pen p = new Pen(Color.Black);//draws wire frame Shapes 
     SolidBrush sb = new SolidBrush(Color.Yellow);//draws filled Shapes 
     Graphics g = panel1.CreateGraphics(); 


     Point[] pointArray = { new Point(100, 20), new Point(100, 0), new Point(120, 0), new Point(120, 20) }; 
     g.FillPolygon(sb, pointArray); 
     g.DrawPolygon(p, pointArray); 
    } 

任何建議將是偉大的!

+1

99%的時間調用'CreateGraphics'是錯誤的。 – leppie

+0

http://stackoverflow.com/a/8312568/340999 – wiero

回答

2

您需要註冊到Paint事件面板,並使用圖形對象自帶的參數:

在構造函數中:

panel1.Paint += new PaintEventHandler(panel1_Paint); 

處理程序本身:

void panel1_Paint(object sender, PaintEventArgs e) { 
{ 
     Pen p = new Pen(Color.Black);//draws wire frame Shapes 
     SolidBrush sb = new SolidBrush(Color.Yellow);//draws filled Shapes 
     Graphics g = e.Graphics; // From Arguments 


     Point[] pointArray = { new Point(100, 20), new Point(100, 0), new Point(120, 0), new Point(120, 20) }; 
     g.FillPolygon(sb, pointArray); 
     g.DrawPolygon(p, pointArray); 
} 
+0

當你想調用它時,執行'panel1.Refresh()' – Kyborek

+1

@Kyborek:'無效'通常是更好的選擇。 'Refresh'立即強制重繪。 – leppie

+0

@leppie無論你想要什麼。只是爲了防止像「它只能使用表單加載,我如何重繪它」? – Kyborek

0

在構造函數中調用此方法時,不能假定子控件和/或圖形對象可用。使用窗體的OnPaint方法或創建一個自定義控件並在其中覆蓋OnPaint。