2011-09-13 55 views
0

我有一個用戶控件,它顯示一個顏色的漸變,它一旦創建就是常量。Windows窗體,在動態生成的位圖上顯示指標

usercontrol不包含任何控件,不知道如果我需要添加一個picturebox或動態添加一個。

在那張圖片上,我想要顯示一條線來顯示當前結果。我在地圖上創建漸變圖像沒有問題,但是我想以某種方式緩存它,所以每次更新指標(從父窗體調用CurrentValue)時,都會將指示線放在漸變圖像上方。這是每秒更新約30次,因此,至於下面的代碼是如何工作的,它每次都在重繪漸變,這是閃爍的。

這裏的一個代碼示例:

namespace Maps.UserControls 
{ 
    public partial class UserControlLegend : UserControl 
    { 
     private double m_CurrentValue; 
     public double CurrentValue 
     { 
      get 
      { 
       return m_CurrentValue; 
      } 
      set 
      { 
       m_CurrentValue = value; 
       RefreshValue(); 
      } 
     } 

     public UserControlLegend() 
     { 
      InitializeComponent(); 
     } 

     private void UserControlLegend_Paint(object sender, PaintEventArgs e) 
     { 
      if (b == null) 
      { 
       g = e.Graphics; 
       b = new System.Drawing.Bitmap(menuWidth, menuHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb); 

       // Code here that draws Menu 

       // Cache bitmap here? 
       g.Dispose(); 
      } 
     } 

     private void RefreshValue() 
     { 
      this.Refresh(); 
      g = this.CreateGraphics(); 
      g.DrawImage(b, 0, 0); 
      //Code to Calcuate current Indicator Location 

      int x3 = 0; 
      // Draws current indicator correctly 
      g.DrawLine(new Pen(new SolidBrush(Color.Black)), this.Width/2 - 15, x3, this.Width/2 - 5, x3); 
      g.Dispose(); 
     } 
    } 
} 
+0

我想通了。我畫了位圖,並且只是使用另一個指標控件,然後將位置移動到指向我想要的位置。效果很好。 – dave2118

回答

0

解釋上述意見,使用位圖,並且只設置x,控制的收率

0

首先,我建議你將你的Control的屬性DoubleBuffered設置爲True,以便閃爍消失。但是,如果您不使用控件本身,那根本就沒用。但是,如果使用PictureBox則更好,因爲它自動爲DoubleBuffered

其次,您每次繪製新的Bitmap,這在內存方面非常糟糕,因爲Bitmap的大小隻有幾兆字節。我建議你在構造函數中初始化一個Bitmap,並在構造函數中創建一個從Bitmap創建的單個Graphics。每當paint accurs,只需清除舊的Graphics g,然後再次繪製它。 g Graphicsb Bitmap應該是Dispose d只有一次,當整個控制是Dispose d。

這可能會增強您的代碼。