2016-02-25 120 views
3

我想繪製圖像到DataVisualization.Charting.Chart的背景。由於ChartArea.BackImage屬性只接受圖像的路徑,因此無法將此值設置爲運行時圖像。繪製Winform圖表的背景而不會覆蓋網格

爲此我把PrePaint Event圖表上繪製圖表圖形(I去除部分代碼和替換爲藍色矩形圖像):

private void chart1_PrePaint(object sender, System.Windows.Forms.DataVisualization.Charting.ChartPaintEventArgs e) 
{ 
    double xMax = e.ChartGraphics.GetPositionFromAxis("ChartArea1", AxisName.X, chart1.ChartAreas[0].AxisX.Maximum); 
    double xMin = e.ChartGraphics.GetPositionFromAxis("ChartArea1", AxisName.X, chart1.ChartAreas[0].AxisX.Minimum); 
    double yMax = e.ChartGraphics.GetPositionFromAxis("ChartArea1", AxisName.Y, chart1.ChartAreas[0].AxisY.Minimum); 
    double yMin = e.ChartGraphics.GetPositionFromAxis("ChartArea1", AxisName.Y, chart1.ChartAreas[0].AxisY.Maximum); 

    double width = xMax-xMin; 
    double heigth = yMax- yMin; 

    RectangleF myRect = new RectangleF((float)xMin,(float)yMin,(float)width,(float)heigth); 
    myRect = e.ChartGraphics.GetAbsoluteRectangle(myRect); 

    e.ChartGraphics.Graphics.FillRectangle(new SolidBrush(Color.LightBlue), myRect); 
} 

的問題是,這圖表網格被覆蓋的方式(見左圖)。但我希望網格可見(見左圖)。有任何想法嗎?

enter image description here

+0

你可以節省你的內存圖像文件在一個臨時目錄,並使用你所提到的'ChartArea.BackImage'財產... – adv12

+0

我會嘗試,但我有點擔心的表現,因爲我想經常更新背景 – RomCoo

+0

是的,這將是一個問題。 – adv12

回答

1

由於ChartArea.BackImage酒店僅接受以圖像的路徑,你不能將此值設置爲一個運行時圖像。

其實你可以通過利用晦澀NamedImage類:

// here you can use any image.. 
Bitmap bmp = ... insert your image creation code! 

// create a named image from it 
NamedImage ni = new NamedImage("test", bmp); 

// add it to the chart's collection of images 
chart1.Images.Add(ni); 

// now we can use it at any place we seemingly can only use a path: 
chart1.BackImage = "test"; 

相同的技巧同樣適用於DataPoint.BackImage

性能雖然是另一個問題,但它應該擊敗寫入磁盤任何時候..