此解决方案使您可以左右拖动注释行,并在(右对齐)标题字段中更新X和Y值。
更新:我已经纠正了一些缩放问题,并添加了可以显示Y值的例程。对此有限制,请参见下文!
为了便于在移动事件中参考,我在类级别声明了一些变量。(您也可以对对象进行强制转换,sender并按名称或索引引用它们。)
ChartArea CA;
Series S1;
VerticalLineAnnotation VA;
RectangleAnnotation RA;
Run Code Online (Sandbox Code Playgroud)
这将创建Annotations:
CA = chart1.ChartAreas[0]; // pick the right ChartArea..
S1 = chart1.Series[0]; // ..and Series!
// factors to convert values to pixels
double xFactor = 0.03; // use your numbers!
double yFactor = 0.02; // use your numbers!
// the vertical line
VA = new VerticalLineAnnotation();
VA.AxisX = CA.AxisX;
VA.AllowMoving = true;
VA.IsInfinitive = true;
VA.ClipToChartArea = CA.Name;
VA.Name = "myLine";
VA.LineColor = Color.Red;
VA.LineWidth = 2; // use your numbers!
VA.X = 1;
// the rectangle
RA = new RectangleAnnotation();
RA.AxisX = CA.AxisX;
RA.IsSizeAlwaysRelative = false;
RA.Width = 20 * xFactor; // use your numbers!
RA.Height = 8 * yFactor; // use your numbers!
VA.Name = "myRect";
RA.LineColor = Color.Red;
RA.BackColor = Color.Red;
RA.AxisY = CA.AxisY;
RA.Y = -RA.Height ;
RA.X = VA.X - RA.Width / 2;
RA.Text = "Hello";
RA.ForeColor = Color.White;
RA.Font = new System.Drawing.Font("Arial", 8f);
chart1.Annotations.Add(VA);
chart1.Annotations.Add(RA);
Run Code Online (Sandbox Code Playgroud)
这将使标签与以下行一起移动:
private void chart1_AnnotationPositionChanging(object sender,
AnnotationPositionChangingEventArgs e)
{
// move the rectangle with the line
if (sender == VA) RA.X = VA.X - RA.Width / 2;
// display the current Y-value
int pt1 = (int)e.NewLocationX;
double step = (S1.Points[pt1 + 1].YValues[0] - S1.Points[pt1].YValues[0]);
double deltaX = e.NewLocationX - S1.Points[pt1].XValue;
double val = S1.Points[pt1].YValues[0] + step * deltaX;
chart1.Titles[0].Text = String.Format(
"X = {0:0.00} Y = {1:0.00}", e.NewLocationX, val);
RA.Text = String.Format("{0:0.00}", val);
chart1.Update();
}
Run Code Online (Sandbox Code Playgroud)
如果要添加此事件以使“线”捕捉到下一个数据点:
private void chart1_AnnotationPositionChanged(object sender, EventArgs e)
{
VA.X = (int)(VA.X + 0.5);
RA.X = VA.X - RA.Width / 2;
}
Run Code Online (Sandbox Code Playgroud)
请注意,Y值的计算假设使用某种线形图形。
我添加了几行以在标签中显示值。如果该文本的长度变化很大,则应该相应地计算标签的宽度!
这是我的示例的快照:
