【问题标题】:Selecting specific values on a Chart在图表上选择特定值
【发布时间】:2017-02-24 15:49:14
【问题描述】:

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

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

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

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

【问题讨论】:

  • 文本块尝试更改它 C# 代码块。
  • 如果您对答案感到满意,请考虑考虑accepting it..! - 我看到你从来没有这样做过:点击左上角的(不可见的)复选标记,在答案的投票下方,然后单击它!它变成绿色并为我们俩赢得了一点声誉。..

标签: c# select charts mschart


【解决方案1】:

要直接点击DataPoint,您可以点击HitTest。但是对于微小的点或范围的选择,这将无法正常工作。

必要的功能隐藏在Axes方法中。

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

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 and Point 图表。对于其他类型,您必须调整选择标准!

【讨论】:

  • 谢谢! ValueToPixelPosition 函数正是我想要的。
  • 一个更快速的问题。由于我使用的是 FastLine 图表,您是否知道任何简单的方法来更改点之间的线条颜色而不是更改点本身的颜色?
  • FastLine 不可能。如果您想要这个和其他额外内容,请使用Line,然后您可以设置每个DataPointColor.. - 如果您对答案感到满意,请考虑accepting 它..!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-19
  • 1970-01-01
  • 1970-01-01
  • 2021-05-01
  • 2015-03-06
相关资源
最近更新 更多