在图表上选择特定值 [英] 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和点
图表。对于其他类型,您必须调整选择标准!
Note that this will work for Line, FastLine and Point
charts. For other types you would have to adapt the selection criterium!
这篇关于在图表上选择特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!