2016-01-13 56 views
0

我有一個自定義控件,其功能是顯示由外部庫創建的圖像。我通過重載OnPaint函數來實現這一點,在那裏生成和繪製圖像。無法在OnPaint方法中清除自定義控件

我的問題是,當我的控件的大小改變,圖像被重新創建和繪製舊圖像仍然可見。

我OnPaint方法比較簡單,因爲圖像創作是在它自己的方法:

protected override void OnPaint(PaintEventArgs e) 
{ 
    base.OnPaint(e); 

    if (image == null || this.Width != image.Width || this.Height != image.Height) 
    { 
     // Remove the old image so we don't accidentally draw it later. 
     this.image = null; 

     // Attempt to clear the control. 
     //e.Graphics.Clear(this.BackColor); 
     e.Graphics.FillRectangle(new SolidBrush(this.BackColor), 0, 0, this.Width, this.Height); 

     try 
     { 
      this.Plot(); // Create my image from the library based on current size. 
     } 
     catch (Exception ex) 
     { 
      SizeF size = e.Graphics.MeasureString(ex.Message, this.Font); 
      e.Graphics.DrawString(ex.Message, this.Font, Brushes.Black, (this.Width - size.Width)/2, (this.Height - size.Height)/2); 
     } 
    } 
    if (this.image != null) 
     e.Graphics.DrawImageUnscaled(image, 0, 0); 
} 

正如你可以看到我已經嘗試了幾件事情要清除包括Graphics.Clear方法控制和我自己重新繪製背景。其中沒有任何影響。

我可以在重繪之前清除我的控制權?

+0

它在繪圖之前調用this.invalidate嗎? –

+0

嗯,我試圖避免在OnPaint中調用它,因爲據我所知,它無效導致重繪,所以我認爲這將創建一個無限循環。 adv12的建議無效調整大小不僅解決了這個問題,但解決了這個問題(我現在接受答案還爲時過早) – Fr33dan

+0

你是對的...有一段時間沒有在winforms上工作,但adv12的答案是好的。 :] –

回答

0

可能發生的情況是,只有部分控制權被無效,因此只有部分控制權被重新粉刷。要解決這個問題,請在其中添加一個Resize事件處理函數,並調用Invalidate()以使整個控件失效並強制進行完整重繪。

編輯:在對問題的評論中,@LarsTech建議設置ResizeRedraw,這是我從未注意過的。這似乎比我建議的Resize事件處理程序更清潔,更符合庫的設計。