Несколько форм с zedgraphs. Линия на одном продолжается, когда начинается следующий

Хорошо, это может быть немного сложно объяснить. У меня есть метод, который вычисляет значения X и Y, которые я хочу построить. Этот метод является чисто внутренним и выполняется внутри фонового рабочего процесса, вызываемого из моего основного потока графического интерфейса.

Отдельно от моей основной формы у меня есть форма, которая содержит только zedgraph и тикер. Я использую эту комбинацию, чтобы отобразить катящуюся X, Y, выплевываемую из моего фонового потока. Это работает нормально, здесь все идет отлично.

Когда я нажимаю кнопку в своем основном графическом интерфейсе, фоновый рабочий процесс закрывается, и zedgraph перестает обновляться. Вот где моя проблема начинается

Когда я нажимаю кнопку «Стоп», график должен оставаться на месте. Он делает это просто отлично ... если это самый первый раз, когда он запускается. На всех будущих графиках это происходит: (Верхнее изображение — это первый график, второе изображение — это второй график.)

график с соединенными первой и последней точкой

Первый график продолжает обновляться, когда это не предполагается. Как мне не допустить этого? Есть ли способ «отключить» первый zedgraph и не дать ему прослушивать новые данные?

Ниже приведен мой код zedgraph, я почти уверен, что проблема где-то здесь, а не в моем основном коде графического интерфейса.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ZedGraph;

namespace RTHERM
{
    public partial class Readout : Form
    {
        // Starting time in milliseconds
        public static float Time_old = 0.0f;
        public static float Tsurf_old;
        public static float Tmidr_old;
        public static float Tcent_old;
        public static float Tenvi_old;

        //  Every "redrawInterval" secods plot a new point (if one is available)
        public static int redrawInterval;
        public int plotRange = 15;      //   Plot will span "plotRange" minutes


        int tickStart = 0;

        public Readout()
        {
            InitializeComponent();
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            //timer1.Equals(0);
            GUI gui = new GUI();
            GraphPane graph = zedGraph.GraphPane;
            graph.Title.Text = GUI.plotTitle;
            graph.XAxis.Title.Text = "Time [min]";
            graph.YAxis.Title.Text = "Temperature [F]";

            graph.Legend.Position = ZedGraph.LegendPos.BottomCenter;
            // Save 1200 points.  At 50 ms sample rate, this is one minute
            // The RollingPointPairList is an efficient storage class that always
            // keeps a rolling set of point data without needing to shift any data values
            RollingPointPairList surfList = new RollingPointPairList(1200);
            //surfList.Clear();
            RollingPointPairList midrList = new RollingPointPairList(1200);
            //midrList.Clear();
            RollingPointPairList centList = new RollingPointPairList(1200);
            //centList.Clear();
            RollingPointPairList furnList = new RollingPointPairList(1200);
            //furnList.Clear();
            // Initially, a curve is added with no data points (list is empty)
            // Color is blue, and there will be no symbols
            LineItem surf = graph.AddCurve("Surface", surfList, Color.DarkBlue, SymbolType.None);
            LineItem midr = graph.AddCurve("Mid-Radius", midrList, Color.DarkOliveGreen, SymbolType.None);
            LineItem cent = graph.AddCurve("Center", centList, Color.DarkOrange, SymbolType.None);
            LineItem furn = graph.AddCurve("Ambient", furnList, Color.Red, SymbolType.None);
            surf.Line.Width = 2;
            midr.Line.Width = 2;
            cent.Line.Width = 2;
            furn.Line.Width = 2;

            // Check for new data points
            timer1.Interval = redrawInterval;
            timer1.Enabled = true;
            //timer1.Start();

            // Just manually control the X axis range so it scrolls continuously
            // instead of discrete step-sized jumps
            graph.XAxis.Scale.Min = 0;
            graph.XAxis.Scale.Max = plotRange;
            graph.XAxis.Scale.MinorStep = 1;
            graph.XAxis.Scale.MajorStep = 5;

            // Scale the axes
            zedGraph.AxisChange();

            // Save the beginning time for reference
            tickStart = Environment.TickCount;
        }

        //  USING A TIMER OBJECT TO UPDATE EVERY FEW MILISECONDS
        private void timer1_Tick(object sender, EventArgs e)
        {
            // Only redraw if we have new information
            if (Transfer.TTIME != Time_old)
            {
                GraphPane graph = this.zedGraph.GraphPane;
                // Make sure that the curvelist has at least one curve
                if (zedGraph.GraphPane.CurveList.Count <= 0)
                    return;

                // Grab the three lineitems
                LineItem surf = this.zedGraph.GraphPane.CurveList[0] as LineItem;
                LineItem midr = this.zedGraph.GraphPane.CurveList[1] as LineItem;
                LineItem cent = this.zedGraph.GraphPane.CurveList[2] as LineItem;
                LineItem furn = this.zedGraph.GraphPane.CurveList[3] as LineItem;

                if (surf == null)
                    return;

                // Get the PointPairList
                IPointListEdit surfList = surf.Points as IPointListEdit;
                IPointListEdit midrList = midr.Points as IPointListEdit;
                IPointListEdit centList = cent.Points as IPointListEdit;
                IPointListEdit enviList = furn.Points as IPointListEdit;

                // If these are null, it means the reference at .Points does not
                // support IPointListEdit, so we won't be able to modify it
                if (surfList == null || midrList == null || centList == null || enviList == null)
                    return;

                // Time is measured in seconds
                double time = (Environment.TickCount - tickStart) / 1000.0;

                // ADDING THE NEW DATA POINTS
                // format is List.Add(X,Y)  Finally something that makes sense!
                surfList.Add(Transfer.TTIME, Transfer.TSURF);
                midrList.Add(Transfer.TTIME, Transfer.TMIDR);
                centList.Add(Transfer.TTIME, Transfer.TCENT);
                enviList.Add(Transfer.TTIME, Transfer.TENVI);

                // Keep the X scale at a rolling 10 minute interval, with one
                // major step between the max X value and the end of the axis
                if (GUI.isRunning)
                {
                    Scale xScale = zedGraph.GraphPane.XAxis.Scale;
                    if (Transfer.TTIME > xScale.Max - xScale.MajorStep)
                    {
                        xScale.Max = Transfer.TTIME + xScale.MajorStep;
                        xScale.Min = xScale.Max - plotRange;
                    }
                }
                // Make sure the Y axis is rescaled to accommodate actual data
                zedGraph.AxisChange();
                // Force a redraw
                zedGraph.Invalidate();
            }
            else return;
        }

        public void reset()
        {
            Time_old = 0.0f;
            Tsurf_old = 0.0f;
            Tmidr_old = 0.0f;
            Tcent_old = 0.0f;
            Tenvi_old = 0.0f;
        }
        private void Form1_Resize(object sender, EventArgs e)
        {
            if (GUI.isRunning)
            {
                SetSize();
            }
        }

        // Set the size and location of the ZedGraphControl
        private void SetSize()
        {
            // Control is always 10 pixels inset from the client rectangle of the form
            Rectangle formRect = this.ClientRectangle;
            formRect.Inflate(-10, -10);

            if (zedGraph.Size != formRect.Size)
            {
                zedGraph.Location = formRect.Location;
                zedGraph.Size = formRect.Size;
            }
        }

        private void saveGraph_Click(object sender, EventArgs e)
        {
            GUI.Pause();
            zedGraph.DoPrint();
            //SaveFileDialog saveDialog = new SaveFileDialog();
            //saveDialog.ShowDialog();
        }

        private void savePlotDialog_FileOk(object sender, CancelEventArgs e)
        {
            // Get file name.
            string name = savePlotDialog.FileName;
            zedGraph.MasterPane.GetImage().Save(name);
            GUI.Resume();
        }

        private bool zedGraphControl1_MouseMoveEvent(ZedGraphControl sender, MouseEventArgs e)
        {
            // Save the mouse location
            PointF mousePt = new PointF(e.X, e.Y);

            // Find the Chart rect that contains the current mouse location
            GraphPane pane = sender.MasterPane.FindChartRect(mousePt);

            // If pane is non-null, we have a valid location.  Otherwise, the mouse is not
            // within any chart rect.
            if (pane != null)
            {
                double x, y;
                // Convert the mouse location to X, and Y scale values
                pane.ReverseTransform(mousePt, out x, out y);
                // Format the status label text
                toolStripStatusXY.Text = "(" + x.ToString("f2") + ", " + y.ToString("f2") + ")";
            }
            else
                // If there is no valid data, then clear the status label text
                toolStripStatusXY.Text = string.Empty;

            // Return false to indicate we have not processed the MouseMoveEvent
            // ZedGraphControl should still go ahead and handle it
            return false;
        }

        private void Readout_FormClosed(object sender, FormClosedEventArgs e)
        {

        }

        private void Readout_FormClosing(object sender, FormClosingEventArgs e)
        {
            //e.Cancel = true;
            //WindowState = FormWindowState.Minimized;
        }
    }
}

person IconRunner    schedule 03.08.2013    source источник
comment
Итак, как вы останавливаете это, вы останавливаете таймер? Ваш код этого не показывает.   -  person bretddog    schedule 06.08.2013


Ответы (1)


Последняя точка соединяется с первой точкой на графике. Я подозреваю, потому что все ваши RollingPointPairList содержат данные несколько раз. Проверьте это, используя точку останова в вашей функции timer1_Tick.

private void Form1_Load вы добавите полный список в файл LineItem.

graph.CurveList.Clear();
LineItem surf = graph.AddCurve("Surface", surfList, Color.DarkBlue, SymbolType.None);
LineItem midr = graph.AddCurve("Mid-Radius", midrList, Color.DarkOliveGreen, SymbolType.None);
LineItem cent = graph.AddCurve("Center", centList, Color.DarkOrange, SymbolType.None);
LineItem furn = graph.AddCurve("Ambient", furnList, Color.Red, SymbolType.None);
person Stefan Bischof    schedule 08.08.2013