c# chart control

本文介绍了一种图表样式的定制方法,包括移除值为零的数据标签、绘制文本、设置滚动条样式等实用技巧,旨在提升图表的视觉效果和用户体验。
internal class ChartStyle
    {
        internal static void RemoveZeroDataPointLabel(Chart chart)
        {
            foreach (Series series in chart.Series)
            {
                foreach (DataPoint dp in series.Points)
                {
                    if (dp.YValues[0].ToString() == "0")
                    {
                        dp.IsValueShownAsLabel = false;
                        dp.Label = " ";
                    }
                }
            }
        }

        internal static void DrawString(object sender, PaintEventArgs e, string text)
        {
            Font font = new Font("微软雅黑", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));

            PictureBox pb = sender as PictureBox;

            float sumY = 0;

            foreach (char c in text)
            {
                string line = new string(c, 1);
                SizeF size = e.Graphics.MeasureString(line, font);
                sumY += size.Height;
            }

            float y = (pb.Height - sumY) / 2;
            y = 10;

            foreach (char c in text)
            {
                string line = new string(c, 1);
                SizeF size = e.Graphics.MeasureString(line, font);
                sumY += size.Height;

                e.Graphics.DrawString(line, font, Brushes.White, (pb.Width - size.Width) / 2, y);
                y += size.Height;
            }
        }

        internal static void chartPickRatio_PostPaint(object sender, ChartPaintEventArgs e)
        {
            e.ChartGraphics.Graphics.SmoothingMode = SmoothingMode.AntiAlias;

            Chart chart = sender as Chart;
            if (chart.Series.Count > 0 && chart.Series[0].Points.Count > 0)
            {
                Series series = chart.Series[0];
                double value = series.Points[0].XValue;
                if (series.Label == "0")
                {
                    value = 0;
                }

                string msg = value.ToString("P0");

                Font font = new Font("Arial", 25);
                SizeF size = e.ChartGraphics.Graphics.MeasureString(msg, font);
                e.ChartGraphics.Graphics.DrawString(msg, font, Brushes.Red,
                    chart.Width / 2 - size.Width / 2,
                    chart.Height / 2 - size.Height / 2);
            }
        }

        /// <summary>
        /// Set Chart ScrollBarStyle
        /// </summary>
        /// <param name="chart"></param>
        internal static void SetChartScrollBarStyle(Chart chart)
        {
            chart.ChartAreas[0].AxisX.ArrowStyle = AxisArrowStyle.Lines;
            //chart.ChartAreas[0].AxisY.ArrowStyle = AxisArrowStyle.Triangle;

            chart.ChartAreas[0].AxisX.ScrollBar.BackColor = Color.Transparent;
            chart.ChartAreas[0].AxisX.ScrollBar.LineColor = chart.ChartAreas[0].AxisX.ScrollBar.ButtonColor = Color.FromArgb(214, 214, 204);

            chart.ChartAreas[0].AxisY.TitleForeColor = Color.White;
            chart.ChartAreas[0].AxisY.TitleFont = new Font("微软雅黑", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            chart.ChartAreas[0].AxisY.TextOrientation = TextOrientation.Stacked;

            chart.ChartAreas[0].AxisY2.TitleForeColor = Color.White;
            chart.ChartAreas[0].AxisY2.TitleFont = new Font("微软雅黑", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));

            if (chart.Tag != "NO")
            {
                chart.ChartAreas[0].InnerPlotPosition.Auto = false;
                chart.ChartAreas[0].InnerPlotPosition.Height = 84.41489F;
                chart.ChartAreas[0].InnerPlotPosition.Width = 85.34175F;
                chart.ChartAreas[0].InnerPlotPosition.X = 9.65825F;
                chart.ChartAreas[0].InnerPlotPosition.Y = 2.79255F;

                //3, 0, 94.8, 97
                chart.ChartAreas[0].InnerPlotPosition.Height = 90;
                chart.ChartAreas[0].InnerPlotPosition.Width = 90;
                chart.ChartAreas[0].InnerPlotPosition.X = 5;
                chart.ChartAreas[0].InnerPlotPosition.Y = 5;

                //chart.ChartAreas[0].InnerPlotPosition.Height = 50;
                //chart.ChartAreas[0].InnerPlotPosition.Width = 50;
                //chart.ChartAreas[0].InnerPlotPosition.X = 15;
                //chart.ChartAreas[0].InnerPlotPosition.Y = 15;
            }

            //chart.ChartAreas[0].InnerPlotPosition.Height = 94.8f;
            //chart.ChartAreas[0].InnerPlotPosition.Height = 90.8f;
            //chart.ChartAreas[0].InnerPlotPosition.Width = 97;
            //chart.ChartAreas[0].InnerPlotPosition.X = 3;
            //chart.ChartAreas[0].InnerPlotPosition.Y = 0;

            chart.ChartAreas[0].AxisY.MajorTickMark.TickMarkStyle = TickMarkStyle.None;
            chart.ChartAreas[0].AxisY2.MajorTickMark.TickMarkStyle = TickMarkStyle.None;
            chart.ChartAreas[0].AxisX.LabelStyle.Enabled = true;

            if (chart.Tag != "NO" && chart.ChartAreas[0].AxisX.ScrollBar.Enabled)
            {
                if (chart.Height > 20)
                {
                    float ratio = 20.0f/(float) chart.Height;
                    chart.ChartAreas[0].InnerPlotPosition.Height -= (ratio*100);
                }
            }

            chart.ChartAreas[0].AxisX.ScrollBar.ButtonStyle = ScrollBarButtonStyles.SmallScroll;
            chart.ChartAreas[0].AxisX.ScrollBar.ButtonColor = Color.White;
        }

        internal static void SetChartScrollBarStyleInForm(Form control)
        {
            List<Control> controlList = new List<Control>();
            GetChildren(controlList, control);

            foreach (Control control1 in controlList)
            {
                if (control1 is Chart)
                {
                    SetChartScrollBarStyle((Chart)control1);
                }
            }
        }

        public static void GetChildren(List<Control> controlList, Control control)
        {
            controlList.Add(control);

            foreach (Control control1 in control.Controls)
            {
                GetChildren(controlList, control1);
            }
        }
    }

 

转载于:https://www.cnblogs.com/liuxinls/archive/2013/05/13/3075252.html

### 创建和自定义曲线图表 在 C# WinForms 应用程序中创建和自定义带有多个 Y 轴的 2D 数据曲线显示控件可以通过使用 `System.Windows.Forms.DataVisualization.Charting` 命名空间中的类来实现[^1]。 #### 添加命名空间引用 为了能够访问 Chart 控件的功能,项目需要添加对 `System.Windows.Forms.DataVisualization.dll` 的引用。这通常通过 NuGet 包管理器安装完成。 #### 初始化 Chart 控件 Chart 控件可以被拖放到设计器上或者编程方式实例化并设置其属性: ```csharp using System; using System.Windows.Forms; using System.Windows.Forms.DataVisualization.Charting; public class CustomChartForm : Form { private Chart chart; public CustomChartForm() { InitializeComponents(); } private void InitializeComponents() { // Create and configure the chart control. chart = new Chart(); chart.Dock = DockStyle.Fill; var chartArea = new ChartArea("Main"); chart.ChartAreas.Add(chartArea); Controls.Add(chart); } } ``` #### 配置多条 Y 轴 对于具有三个独立 Y 轴的需求,在 ChartArea 对象内配置额外的 AxisY 实例,并指定它们的位置以及关联的数据序列: ```csharp // Add primary Y axis (left side). chartArea.AxisY.Title = "Primary Voltage"; chartArea.AxisY.LineColor = Color.Black; // Add secondary Y axes on right side of plot area. var yAxisSecondaryCurrent = new Axis("AxisY2", AxisName.Y, true); yAxisSecondaryCurrent.Title = "Current"; yAxisSecondaryCurrent.LineColor = Color.Blue; chartArea.AxisY2.Enabled = AxisEnabled.True; chartArea.AxisY2.MajorGrid.LineDashStyle = ChartDashStyle.DashDot; chartArea.AxisY2.LabelAutoFitMinFontSize = 8; var yAxisTertiaryPower = new Axis("AxisY3", AxisName.Y, false); yAxisTertiaryPower.Title = "Power"; yAxisTertiaryPower.LineColor = Color.Red; chartArea.AxisY3.Enabled = AxisEnabled.True; chartArea.AxisY3.IsStartedFromZero = false; chartArea.AxisY3.IntervalOffsetType = DateTimeIntervalType.Number; ``` #### 绘制实时更新的电压电流轨迹曲线 为了让图表支持动态数据输入,可以在后台线程定时向 Series 中追加新点位,同时移除过期的数据点保持窗口滚动效果: ```csharp private Timer timerUpdateDataPoints; private Random randomGenerator = new(); timerUpdateDataPoints = new(100); timerUpdateDataPoints.Elapsed += OnTimerTick; timerUpdateDataPoints.Start(); void OnTimerTick(object sender, EventArgs e) { double voltageValue = GetVoltageReading(); // Replace with actual data source method call double currentValue = GetCurrentReading(); // Replace with actual data source method call seriesVoltage.Points.AddXY(DateTime.Now.ToOADate(), voltageValue); seriesCurrent.Points.AddXY(DateTime.Now.ToOADate(), currentValue); if(seriesVoltage.Points.Count > MAX_POINTS){ seriesVoltage.Points.RemoveAt(0); seriesCurrent.Points.RemoveAt(0); } this.Invoke((MethodInvoker)this.chart.Invalidate); } double GetVoltageReading(){ return Math.Sin(randomGenerator.NextDouble()) * VOLTAGE_AMPLITUDE + BASE_VOLTAGE_LEVEL; } double GetCurrentReading(){ return Math.Cos(randomGenerator.NextDouble()) * CURRENT_AMPLITUDE + BASE_CURRENT_LEVEL; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值