【问题标题】:Drawing on the background of a Winform Chart without overpainting the grid在 Winform 图表的背景上绘制而不覆盖网格
【发布时间】:2016-06-08 22:07:40
【问题描述】:

我想在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 属性...
  • 我会试试,但我有点担心性能,因为我想经常更新背景
  • 是的,这将是一个问题。

标签: c# winforms charts data-visualization


【解决方案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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-13
    • 1970-01-01
    • 2014-10-03
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-19
    相关资源
    最近更新 更多