How to display X-Axis and Y-Axis values when move

2020-02-02 03:22发布

How can I display the values of X-Axis and Y-Axis when the mouse is moved anywhere within the chart area (like the picture)?

enter image description here

The HitTest method can not be applied for moving or it can only be applied for clicking on the chart?

Please help me. Thanks in advance.

The tooltip shows data outside the real area data drawn

标签: c# charts
1条回答
Summer. ? 凉城
2楼-- · 2020-02-02 03:49

Actually the Hittest method works just fine in a MouseMove; its problem is that it will only give a hit when you are actually over a DataPoint.

The Values on the Axes can be retrieved/converted from pixel coordinates by these axis-functions:

ToolTip tt = null;
Point tl = Point.Empty;

private void chart1_MouseMove(object sender, MouseEventArgs e)
{
    if (tt == null )  tt = new ToolTip();

    ChartArea ca = chart1.ChartAreas[0];

    if (InnerPlotPositionClientRectangle(chart1, ca).Contains(e.Location))
    {

        Axis ax = ca.AxisX;
        Axis ay = ca.AxisY;
        double x = ax.PixelPositionToValue(e.X);
        double y = ay.PixelPositionToValue(e.Y);
        string s = DateTime.FromOADate(x).ToShortDateString();
        if (e.Location != tl)
            tt.SetToolTip(chart1, string.Format("X={0} ; {1:0.00}", s, y));
        tl = e.Location;
    }
    else tt.Hide(chart1);
}

Note that they will not work while the chart is busy laying out the chart elements or before it has done so. MouseMove is fine, though.

enter image description here

Also note that the example displays the raw data while the x-axis labels show the data as DateTimes. Use

string s = DateTime.FromOADate(x).ToShortDateString();

or something similar to convert the values to dates!

The check for being inside the actual plotarea uses these two useful functions:

RectangleF ChartAreaClientRectangle(Chart chart, ChartArea CA)
{
    RectangleF CAR = CA.Position.ToRectangleF();
    float pw = chart.ClientSize.Width / 100f;
    float ph = chart.ClientSize.Height / 100f;
    return new RectangleF(pw * CAR.X, ph * CAR.Y, pw * CAR.Width, ph * CAR.Height);
}

RectangleF InnerPlotPositionClientRectangle(Chart chart, ChartArea CA)
{
    RectangleF IPP = CA.InnerPlotPosition.ToRectangleF();
    RectangleF CArp = ChartAreaClientRectangle(chart, CA);

    float pw = CArp.Width / 100f;
    float ph = CArp.Height / 100f;

    return new RectangleF(CArp.X + pw * IPP.X, CArp.Y + ph * IPP.Y,
                            pw * IPP.Width, ph * IPP.Height);
}

If you want to you can cache the InnerPlotPositionClientRectangle; you need to do so when you change the data layout or resize the chart.

查看更多
登录 后发表回答