在图表上选择特定值

我正在尝试使用我的图表上的数据创建一种复制和粘贴function,我想知道在点击图表时是否有任何方法可以获得图表上某点的x位置?

基本上,我们的想法是能够单击图形的一部分并拖动以选择一个区域,然后我将相应地处理该区域。

因此,我需要能够找出用户点击图表的位置,以确定所选区域的第一个点是什么。

我查看了图表API,但我似乎找不到任何有用的这类问题..

要直接单击DataPoint您可以执行HitTest 。 但是对于小点或选择范围,这将不会很好。

必要的函数隐藏在Axes方法中。

此解决方案使用常规橡皮筋矩形来选择捕获的点:

在此处输入图像描述

 Point mdown = Point.Empty; List selectedPoints = null; private void chart1_MouseDown(object sender, MouseEventArgs e) { mdown = e.Location; selectedPoints = new List(); } private void chart1_MouseMove(object sender, MouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Left) { chart1.Refresh(); using (Graphics g = chart1.CreateGraphics()) g.DrawRectangle(Pens.Red, GetRectangle(mdown, e.Location)); } } private void chart1_MouseUp(object sender, MouseEventArgs e) { Axis ax = chart1.ChartAreas[0].AxisX; Axis ay = chart1.ChartAreas[0].AxisY; Rectangle rect = GetRectangle(mdown, e.Location); foreach (DataPoint dp in chart1.Series[0].Points) { int x = (int)ax.ValueToPixelPosition(dp.XValue); int y = (int)ay.ValueToPixelPosition(dp.YValues[0]); if (rect.Contains(new Point(x,y))) selectedPoints.Add(dp); } // optionally color the found datapoints: foreach (DataPoint dp in chart1.Series[0].Points) dp.Color = selectedPoints.Contains(dp) ? Color.Red : Color.Black; } static public Rectangle GetRectangle(Point p1, Point p2) { return new Rectangle(Math.Min(p1.X, p2.X), Math.Min(p1.Y, p2.Y), Math.Abs(p1.X - p2.X), Math.Abs(p1.Y - p2.Y)); } 

请注意,这适用于Line, FastLine and Point图表。 对于其他类型,您将不得不调整选择标准!