2016-10-29 251 views
0

当鼠标在图表区域内的任何地方(如图片)移动 时,如何显示X轴和Y轴的值?移动鼠标时如何显示X轴和Y轴的值?

enter image description here

HitTest方法不能应用于移动或它只能适用于点击图上?

请帮帮我。提前致谢。

The tooltip shows data outside the real area data drawn

+0

如果这是一个WinForms应用程序,那么你可以处理'Control.MouseMove'事件。 MouseEventArgs参数包含X和Y属性。 –

+0

是的,我在WinForms中使用Chart。 –

+0

你解决了你的问题吗? – TaW

回答

0

其实Hittest方法工作在MouseMove就好了;它的问题在于,只有当你实际上是而不是 a DataPoint时才会发生。

的上AxesValues可以检索/从像素转换的坐标由这些轴功能:

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); 
} 

注意,它们将不起作用图表是忙摆出图表元素或之前它已经这样做了。尽管如此,MouseMove没问题。

enter image description here

还要注意,示例显示的原始数据,而x轴标签显示数据作为DateTimes。使用

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

或类似的东西将值转换为日期!

为是实际plotarea内的支票使用这两个实用的功能:

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); 
} 

如果你愿意,你可以缓存InnerPlotPositionClientRectangle;您在更改数据布局或调整图表大小时需要这样做。

+0

非常感谢!它运作良好。但是,它有一个问题:当我将鼠标移动到图表外部时,该区域包含绘制的实际数据,工具提示也显示数据,这不是我需要的东西。你有解决方案吗? –

+0

啊,是的。你是对的。我们需要添加一个检查内部Charatarea的Innerplotposition ..我已经更新了答案.. – TaW

+0

太棒了!谢谢亲!它效果很好^^ –