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

百般思念 提交于 2019-12-28 07:08:12

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/40315455/how-to-display-x-axis-and-y-axis-values-when-move-the-mouse

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!