在Winform Chart的背景上绘制而不会过度绘制网格

时间:2016-02-25 21:50:05

标签: c# winforms charts data-visualization

我想将图像绘制到DataVisualization.Charting.Chart的背景中。由于ChartArea.BackImage属性仅接受图像的路径,因此无法将此值设置为运行时图像。

出于这个原因,我拿图表的PrePaint Event绘制图表图形(我删除了部分代码并用蓝色矩形替换了图像):

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

1 个答案:

答案 0 :(得分:2)

由于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

性能是另一个问题,但它应该随时写入磁盘......