在winform项目中为图表添加十字准线

本文关键字:十字 添加 项目 winform | 更新日期: 2023-09-27 18:17:13

我刚开始使用c#中的图表,问题是,我不知道如何在图表中添加十字准星?我的项目是一个使用c#的winform应用程序。

在winform项目中为图表添加十字准线

感谢大家,但我找到了下面的解决方案:

cursor_Y = Chart1.ChartAreas["ChartArea1"].CursorY;
cursor_X = Chart1.ChartAreas["ChartArea1"].CursorX;
cursor_Y.LineWidth = 2;
cursor_Y.LineDashStyle = ChartDashStyle.DashDot;
cursor_Y.LineColor = Color.Red;
cursor_Y.SelectionColor = Color.Yellow;
cursor_X.LineWidth = 2;
cursor_X.LineDashStyle = ChartDashStyle.DashDot;
cursor_X.LineColor = Color.Red;
Chart1.MouseMove += new MouseEventHandler(Chart1_MouseMove);
...
PointF _point = new PointF(2,2);
void Chart1_MouseMove(object sender, MouseEventArgs e)
{
    _point.X = e.Location.X;
    _point.Y = e.Location.Y;
    Chart1.ChartAreas["ChartArea1"].CursorY.SetCursorPixelPosition(_point, true);
    Chart1.ChartAreas["ChartArea1"].CursorX.SetCursorPixelPosition(_point, true);
}

很简单,只需重写图表的OnPaint方法,或者订阅Paint事件和图表的MouseMove事件。

所以你会有这样的东西:

Point MouseLocation;
private void MouseMove(object sender, MouseEventArgs e)
{
    MouseLocation = e.Location;
    Invalidate();
}
private void Paint(object sender, PaintEventArgs e)
{
    g.DrawLine(Pens.Black, new Point(0, MouseLocation.Y), new Point(Width, MouseLocation.Y));
    g.DrawLine(Pens.Black, new Point(MouseLocation.X, 0), new Point(MouseLocation.X, Height));
}

为了使它更平滑,你需要查看双缓冲和设置区域中的线条,并使需要重绘的区域无效。

还可以使虚线看起来像创建自己的钢笔

只需创建两个标签框lab_X_Axislab_Y_Axis。图中鼠标移动函数代码如下图所示…

private void chart1_MouseMove(object sender, MouseEventArgs e)
{
    lab_X_Axis.Location = new Point((e.X), 21);
    lab_Y_Axis.Location = new Point(76, e.Y);
}
private void Form1_Load(object sender, EventArgs e)
{
    lab_X_Axis.AutoSize = false;
    lab_Y_Axis.AutoSize = false;
    lab_X_Axis.Text="";
    lab_Y_Axis.Text="";
    lab_X_Axes.Size = new Size(1, 300);
    lab_Y_Axes.Size = new Size(300, 1);
}