2016-02-25 133 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

性能虽然是另一个问题,但它应该击败写入磁盘任何时候..