简体   繁体   中英

How to display X-Axis and Y-Axis values when move the mouse?

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)?

在此处输入图片说明

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

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.

在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM