在不过度绘制网格的情况下绘制 Winform 图表的背景

Drawing on the background of a Winform Chart without overpainting the grid

我想在 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);
}

问题是,这样图表的网格就会被覆盖(见左图)。但我希望网格可见(见左图)。有什么想法吗?

由于 ChartArea.BackImage 属性 只接受图像的路径,您不能将此值设置为运行时图像。

实际上你可以通过使用晦涩的NamedImage class:

// 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 = ni.Name;

同样的技巧也适用于 DataPoint.BackImage !

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