-1

我有一个关于 ms 图表的问题:如何在鼠标移动事件中获取 CursorX 数据点?

4

1 回答 1

0

假设您的图表被调用_chart并且您所追求的图表的索引是CHART_INDEX

首先,从 X 像素坐标计算 X 轴坐标:

// Assume MouseEventArgs e is passed in from (for example) chart_MouseDown():
var xAxis = _chart.ChartAreas[CHART_INDEX].AxisX;
double x = xAxis.PixelPositionToValue(e.Location.X);

现在x是 X 轴上像素的 X 坐标(以 X 轴为单位)。

然后,您必须确定距离 X 轴值最近的先前数据点。

假设这SERIES_INDEX是您感兴趣的系列的索引:

private double nearestPreceedingValue(double xCoord)
{
    // Find the last  at or before the current xCoord.
    // Since the data is ordered on X, we can binary search for it.

    var data  = _chart.Series[SERIES_INDEX].Points;
    int index = data.BinarySearch(xCoord, (xVal, point) => Math.Sign(xCoord - point.XValue));

    if (index < 0)
    {
        index = ~index;               // BinarySearch() returns the index of the next element LARGER than the target.
        index = Math.Max(0, index-1); // We want the value of the previous element, so we must decrement the returned index.
    }                                 // If this is before the start of the graph, use the first valid data point.

    // Return -1 if not found, or the value of the nearest preceeding point if found.
    // (Substitute an appropriate value for -1 if you need a different "invalid" value.)

    return (index < data.Count) ? (int)data[index].YValues[0] : -1;
}
于 2013-07-23T10:11:19.297 回答