选择图表上的特定值 [英] Selecting specific values on a Chart
问题描述
我正在尝试使用图表上的数据创建一种复制和粘贴功能,我想知道是否有任何方法可以在单击图表时获取图表上某个点的 x 位置?
I'm trying to create a sort of copy and paste function with the data on my graph and I was wondering if there was any way to get the x position of a point on the chart when it is clicked?
基本上,这个想法是能够单击图形的一部分并拖动以选择一个区域,然后我将相应地处理该区域.
Basically, the idea is to be able to click a portion of the graph and drag to select an area, which I will then process accordingly.
因此,我需要能够弄清楚用户在图表上单击的位置以确定所选区域的第一个点将是什么.
So, I need to be able to figure out where on the graph the user has clicked to determine the what the first point of the selected area will be.
我浏览了图表 API,但我似乎找不到任何对此类问题有用的东西..
I looked through the chart API, but I couldn't seem to find anything useful for this type of problem..
推荐答案
对于直接单击 DataPoint
,您可以执行 HitTest
.但是对于微小的点或范围的选择,这将不起作用.
For directly clicking on a DataPoint
you can do a HitTest
. But for tiny points or for a selection of a range this will not work well.
必要的功能隐藏在 Axes
方法中.
The necessary functions are hidden in the Axes
methods.
此解决方案使用常规橡皮筋矩形来选择捕获的点:
This solution uses a regular rubber-band rectangle to select the points caught:
Point mdown = Point.Empty;
List<DataPoint> selectedPoints = null;
private void chart1_MouseDown(object sender, MouseEventArgs e)
{
mdown = e.Location;
selectedPoints = new List<DataPoint>();
}
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 和 Point
图表.对于其他类型,您必须调整选择标准!
Note that this will work for Line, FastLine and Point
charts. For other types you would have to adapt the selection criterium!
这篇关于选择图表上的特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!