折线图矩形注释根据点数调整大小

时间:2014-09-15 10:31:36

标签: c# winforms charts annotations linechart

我有折线图。我从数据库中读取一个值及其记录时间,然后每秒将其添加到折线图中。所以我的分数每秒都在增加。

问题在于。我在线图中添加了一个直线和矩形的公式。线条开始保持与开始时相同的宽度,但矩形公式的宽度根据我添加的点数而变化。

喜欢这个;

enter image description here enter image description here

我只想要那个矩形公式有一个固定的宽度我该怎么做?

代码;

    VerticalLineAnnotation VA;
    RectangleAnnotation RA;
    double xFactor = 0.03;
    double yFactor = 0.02;


    VA = new VerticalLineAnnotation();
    VA.AxisX = chartMonitor.ChartAreas[0].AxisX;
    VA.AllowMoving = true;
    VA.IsInfinitive = true;
    VA.ClipToChartArea = chartMonitor.ChartAreas[0].Name;
    VA.Name = "myLine";
    VA.LineColor = Color.Red;
    VA.LineWidth = 2;
    VA.X = 1;


    RA = new RectangleAnnotation();
    RA.AxisX = chartMonitor.ChartAreas[0].AxisX;
    RA.IsSizeAlwaysRelative = false;
    RA.Width = 10 * xFactor;
    RA.Height = 30 * yFactor;
    VA.Name = "myRect";
    RA.LineColor = Color.Red;
    RA.BackColor = Color.Red;
    RA.AxisY = chartMonitor.ChartAreas[0].AxisY;
    RA.Y = -RA.Height;
    RA.X = VA.X - RA.Width / 2;

    RA.Text = "M1";
    RA.ForeColor = Color.White;
    RA.Font = new System.Drawing.Font("Arial", 8f);

    chartMonitor.Annotations.Add(VA);
    chartMonitor.Annotations.Add(RA);
    chartMonitor.AnnotationPositionChanged += new EventHandler(chartMonitor_AnnotationPositionChanged);
    chartMonitor.AnnotationPositionChanging += new EventHandler<AnnotationPositionChangingEventArgs>(chartMonitor_AnnotationPositionChanging);

void chartMonitor_AnnotationPositionChanging(object sender, AnnotationPositionChangingEventArgs e)
        {
            if (sender == VA) RA.X = VA.X - RA.Width / 2;
        }

        void chartMonitor_AnnotationPositionChanged(object sender, EventArgs e)
        {
            VA.X = (int)(VA.X + 0.5);
            RA.X = VA.X - RA.Width / 2;
        }

1 个答案:

答案 0 :(得分:0)

我想我记得那段代码..

Annotation绑定到X轴,这意味着它的大部分属性都是用X轴值测量的。 (不是LineWidth,它是像素或FontSize,它像往常一样工作..)

我已经包含了一个因素,可以让您根据需要进行扩展。

假设某个值f1 = 0.03适用于N1个数据点,您需要重新计算N2个数据点,如下所示:

 xFactor = f1 * N1 / N2;

因此,您应该引入const f1并在添加或删除绘图点时重新计算因子..

这是一个能够做到这一点的功能:

 void scaleAnnotation(Annotation A)
 {
     ChartArea CA = chart1.ChartAreas[0];// pick your chartarea..
     A.AxisX = CA.AxisX;                 // .. and axis!
     int N = S1.Points.Count;            // S1 being your Series !
     // to keep the label width constant the chart's width must be considered
     // 60 is my 'magic' number; you must adapt for your chart's x-axis scale!
     double xFactor = 60 * N / chart1.Width;   
     A.Width = 1 * xFactor ;
     A.X = VA.X - A.Width / 2;    
 }

我发现即使在调整图表大小时,添加10.000点并逐一删除它们,标签的宽度也非常稳定。

注意:您必须使xFactor适应图表的x值标准;做一些测试..! 我发现每次添加一个点时调用它都会使标签保持相当恒定的大小,即使图表本身有很多点。

相关问题