C# 调用mschart控件

由于网上有很多关于mschart安装及注册的信息,在这里我就不在累述,默认大家已经下载、安装并完成注册。
最近为了美化form界面,我接触到这款控件,在这里先撰写一下,自己这两天学习心得。vs用的是2017版
mschart是一款功能强大的绘图工具,可以根据不同的需要绘制相应的图形,基本满足了广大用户的需求。为了适应我做工程的需要,需要自己对控件绘图进行适当的修改,因此这篇文档,主要围绕这我自己的需要进行界面修改展开,此次修改的主要两个点在于:
1.给横纵坐标添加了相应的坐标箭头,自己设置箭头的大小;
2.根据需要在Y轴上绘制不等间距的Y轴线,并可以在合适的位置加入自己想要加入的字符;
3.保存图片的功能
先贴出效果图:(由于截图工具原因使得图片线条颜色发生了改变)
C# 调用mschart控件_第1张图片
核心代码如下:

//清空原来数据缓存
            Chart1.Series[0].Points.Clear();

            //定义图表大小尺寸
            Chart1.Width = Panel1.Width + 580;
            Chart1.Height = Panel1.Height;
            
            //添加图表标题、字体、字号
            //Title title = new Title();//添加图表标题
            //title = chart1.Titles.Add("CreatByQihanWang");
            //title.Font = new Font("宋体", 20);//字体、字号
            //title.Alignment = ContentAlignment.TopCenter;//显示位置

            //chart1.Titles.
            //定义X轴、Y轴数据
            double[] Ydata = { 2, 3, 5, 99 };
            DateTime[] Xdate = new DateTime[] { DateTime.Parse("05:13:20"), DateTime.Parse("07:00"), DateTime.Parse("08:10"), DateTime.Parse("09:20") };
            //string[,] ab = new string[1, 2];
            //ab[0, 0] = "05:30:20";ab[0, 1] = "05:30:40";
            //for (int i = 0; i < ab.Length; i++)
            //{
            //    DateTime[] Xdata = new DateTime[] { DateTime.Parse(ab[0, i]) };//可以通过读取数据库数据的形式导入时间数据
            //}

            //以下按照先绘制chartArea、然后再绘制Series的步骤画图
            //chartArea背景颜色
            Chart1.BackColor = Color.Azure;

            #region X轴设置
            //X轴设置
            Chart1.ChartAreas[0].AxisX.Title = "时间";
            Chart1.ChartAreas[0].AxisX.TitleAlignment = StringAlignment.Center;
            //chart1.ChartAreas[0].AxisX.MajorGrid.LineWidth = 2;//设置线宽2
            //chart1.ChartAreas[0].AxisX.MinorGrid.LineWidth = 2;//设置线宽2
            Chart1.ChartAreas[0].AxisX.MajorGrid.Enabled = true;//显示竖着的主分割线
            Chart1.ChartAreas[0].AxisX.MajorGrid.LineDashStyle = ChartDashStyle.Dash;//设置主网格为虚线
            //chart1.ChartAreas[0].AxisX.MinorGrid.Enabled = true;//显示竖着的次分割线
            //chart1.ChartAreas[0].AxisX.MinorGrid.LineDashStyle = ChartDashStyle.Dash;//设置网格为虚线

            //chart1.ChartAreas[0].CursorX.AutoScroll = AutoScroll;// CursorX.AutoScroll
            //chart1.ChartAreas[0].CursorY.AutoScroll = AutoScroll;
            //chart1.ChartAreas[0].AxisX.ScrollBar.IsPositionedInside = false;//设置滚动条是在外部显示
            //chart1.ChartAreas[0].AxisX.ScrollBar.Size = 20;//设置滚动条的宽度
            //chart1.ChartAreas[0].AxisX.ScrollBar.ButtonStyle = ScrollBarButtonStyles.SmallScroll;//滚动条只显示向前的按钮,主要是为了不显示取消显示的按钮
            //chart1.ChartAreas["ChartArea1"].AxisX.ScaleView.Size = 10;//设置图表可视区域数据点数,说白了一次可以看到多少个X轴区域
            //Chart1.ChartAreas[0].AxisY.LabelStyle.Format = "";
                   
            Chart1.ChartAreas[0].AxisX.LabelStyle.Format = "HH:mm"; //X轴显示的时间格式,HH为大写时是24小时制,hh小写时是12小时制
            Chart1.ChartAreas[0].AxisX.Minimum = DateTime.Parse("05:00").ToOADate();
            Chart1.ChartAreas[0].AxisX.Maximum = DateTime.Parse("23:30").ToOADate();
            Chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Minutes;//如果是时间类型的数据,间隔方式可以是秒、分、时
            Chart1.ChartAreas[0].AxisX.Interval = DateTime.Parse("00:30").Minute;//              
            Chart1.ChartAreas[0].AxisX.MajorGrid.LineDashStyle = ChartDashStyle.Dash;//设置网格为虚线
            Chart1.ChartAreas[0].AxisX.MajorTickMark.Enabled = false;
            #endregion

            //Y轴设置
            #region 不等间隔分Y轴
            //chart1.ChartAreas[0].AxisY.IsLabelAutoFit = false;
            //chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
            //chart1.ChartAreas[0].AxisY.MajorTickMark.Enabled = false;
            //chart1.ChartAreas[0].AxisY.LabelStyle.ForeColor = System.Drawing.Color.Transparent; //這個只有第二種顯示方式才需要,第一種會直接蓋掉
            //chart1.ChartAreas[0].AxisY.Maximum = 100;
            //chart1.ChartAreas[0].AxisY.CustomLabels.Add(0, 20, "20");
            //chart1.ChartAreas[0].AxisY.CustomLabels.Add(21, 60, "60");
            //chart1.ChartAreas[0].AxisY.CustomLabels.Add(61, 80, "61~80");
            //chart1.ChartAreas[0].AxisY.CustomLabels.Add(81, 100, "81~100");
            //CustomLabel cl1 = new CustomLabel(20, 20, "20", 1, LabelMarkStyle.SideMark);
            //CustomLabel cl2 = new CustomLabel(21, 60, "60", 1, LabelMarkStyle.SideMark);
            ////參數依序為(開始位置,結束位置,顯示文字,位置Index(0就是靠近Y軸,數字愈大就往左移),顯示方式)
            //cl1.ForeColor = Color.Black;
            //cl2.ForeColor = Color.Black;
            //CustomLabel label1 = new CustomLabel();
            //label1.Text = "20";
            ////chart1.ChartAreas[0].AxisY.CustomLabels.Add(20, 20, "20");
            //chart1.ChartAreas[0].AxisY.CustomLabels.Add(cl1);
            ////chart1.ChartAreas[0].AxisY.CustomLabels.Add(cl2);
            ////CustomLabel cl3 = new CustomLabel((0,20));
            //StripLine sl1 = new StripLine();
            //sl1.BackColor = Color.Black; //格線黑色
            //sl1.IntervalOffset = 20;//顯示在Y軸值=20的地方
            //sl1.StripWidth = 1;//線寬
            //chart1.ChartAreas[0].AxisY.StripLines.Add(sl1);//把它加到AxisY裡去

            //StripLine sl2 = new StripLine();
            //sl2.BackColor = Color.Black; //格線黑色
            //sl2.IntervalOffset = 23;//顯示在Y軸值=60的地方
            //sl2.StripWidth = 1;//線寬
            //chart1.ChartAreas[0].AxisY.StripLines.Add(sl2);//把它加到AxisY裡去
            #endregion

            #region 等分Y轴
            //Chart1.ChartAreas[0].AxisY.Title = "车站";
            //Chart1.ChartAreas[0].AxisY.TitleAlignment = StringAlignment.Center;
            //Chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = true;//显示横着的分割线
            //Chart1.ChartAreas[0].AxisY.MajorGrid.LineDashStyle = ChartDashStyle.Dash;//设置网格为虚线
            //Chart1.ChartAreas[0].AxisY.MajorTickMark.Enabled = false;
            //Chart1.ChartAreas[0].AxisY.Minimum = 0;
            //Chart1.ChartAreas[0].AxisY.Maximum = 80;
            //Chart1.ChartAreas[0].AxisY.Interval = 10;

            //Chart1.ChartAreas[0].AxisY2.Minimum = 0;
            //Chart1.ChartAreas[0].AxisY2.Maximum = 80;
            //Chart1.ChartAreas[0].AxisY2.Interval = 10;

            //AxisY:
            //{
            //    tickPositions: [0, 20, 50, 100] // 指定竖轴坐标点的值
            //}          
            #endregion

            #region Series绘制
            //Series绘制
            Chart1.Series[0].LegendText = "";//图表标题
            Chart1.Series[0].ChartType = SeriesChartType.Spline;//图表的类型
            Chart1.Series[0].XValueType = ChartValueType.DateTime;//X轴值数据类型
            Chart1.Series[0].IsValueShownAsLabel = true;//显示数据点的值
            Chart1.Series[0].MarkerStyle = MarkerStyle.Circle;//设置点的形状为圆
            Chart1.Series[0].IsVisibleInLegend = false;//将图表标题进行隐藏
            #endregion

            #region 修改Y轴大小
            //Series s = chart1.Series[0];
            //ChartArea ca = chart1.ChartAreas[0];
            //Axis ay = ca.AxisY;           
            //ay.ScaleBreakStyle.Enabled = true;   // <<<=== enable or disable!
            //ay.ScaleBreakStyle.LineWidth = 1;
            //ay.ScaleBreakStyle.LineColor = Color.OrangeRed;
            //ay.ScaleBreakStyle.StartFromZero = StartFromZero.Auto;
            //ay.ScaleBreakStyle.Spacing = 2;
            //ay.ScaleBreakStyle.StartFromZero = StartFromZero.Auto;
            #endregion

            #region 修改X轴大小
            //Series s = chart1.Series[0];
            //ChartArea ca = chart1.ChartAreas[0];
            //Axis ay = ca.AxisX;
            //ay.ScaleBreakStyle.Enabled = true;
            //ay.ScaleBreakStyle.LineWidth = 1;
            //ay.ScaleBreakStyle.LineColor = Color.OrangeRed;
            //ay.ScaleBreakStyle.StartFromZero = StartFromZero.Auto;
            //ay.ScaleBreakStyle.Spacing = 2;
            //ay.ScaleBreakStyle.StartFromZero = StartFromZero.Auto;
            #endregion

            //把数据点添加到Series图表中
            for (int i = 0; i < Xdate.Length; i++)
            {
                Chart1.Series[0].Points.AddXY(Xdate[i], Ydata[i]);//导入数据
            }
            Panel1.AutoScroll = true;
            this.Panel1.Controls.Add(Chart1); //将表放入panel控件中 
            #region 
            //////////////////////ChartArea1属性设置///////////////////////////
            //chart1.Width = panel1.Width + 1050;
            //chart1.Height = panel1.Height + 1050;
            ////设置网格的颜色
            //chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.LineColor = Color.LightGray;
            //chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.LineColor = Color.LightGray;
            ////设置坐标轴名称
            //chart1.ChartAreas["ChartArea1"].AxisX.Title = "随机数";
            //chart1.ChartAreas["ChartArea1"].AxisY.Title = "数值";
            ////启用3D显示
            //chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = false;
            ////////////////////////Series属性设置///////////////////////////
            ////设置显示类型-线型
            //chart1.Series["随机数"].ChartType = SeriesChartType.Line;
            ////设置坐标轴Value显示类型
            //chart1.Series["随机数"].XValueType = ChartValueType.Time;
            ////chart1.Series["随机数"].XAxisType = ChartValueType.DateTime;
            ////是否显示标签的数值
            //chart1.Series["随机数"].IsValueShownAsLabel = true;
            ////设置标记图案
            //chart1.Series["随机数"].MarkerStyle = MarkerStyle.Circle;
            ////设置图案颜色
            //chart1.Series["随机数"].Color = Color.Green;
            ////设置图案的宽度
            //chart1.Series["随机数"].BorderWidth = 3;
            ////添加随机数
            //Random rd = new Random();

            //for (int i = 1; i < 20; i++)
            //{
            //    //chart1.Series["随机数"].Points.AddXY("5:00");
            //    chart1.Series["随机数"].Points.AddXY(i, rd.Next(100));
            //    //chart1.Series["随机数"].Points.AddX( rd.Next(100));
            //}
            ////其实没有必要,可以使用chart1。ChartAreas[0]就可以了
            ////chart1.ChartAreas.Add(chartArea1);

            ////完成Chart和chartArea的关联
            //System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
            //legend1.Name = "图标";
            //chart1.Legends.Add(legend1);
            //chart1.Name = "chart1";
            //series1.ChartType = SeriesChartType.Spline;

            ////设置线性
            //Random rd = new Random();
            //double[] num = new double[20];

            //for (int i = 0; i < 20; i++)
            //{
            //    int valuey = rd.Next(20, 100);
            //    //
            //    series1.Points.AddXY(i, rd.Next(100));
            //    //DataPoint point = new DataPoint((i + 1), valuey);
            //    //series1.Points.Add(point);
            //    //DataPoint point = new DataPoint();
            //    //point = ((i + 1), valuey);
            //    //series1.Points.Add(point);
            //}

            ////产生点的坐标
            ////chart1.Titles[0].Text = "";

            //series1.ChartArea = "ChartArea1";
            //chartArea1.AxisX.Title = "日期";
            //chartArea1.AxisY.Title = "值";
            //chartArea1.AxisX.Interval = 1;
            //chartArea1.AxisY.Interval = 5;
            //chartArea1.AxisY.Minimum = 20;
            //series1.Legend = "图标";
            //series1.Name = "Series1";
            //chart1.Text = "测试";
            //chart1.Size = new System.Drawing.Size(700, 500);
            ////chart1.Location = new System.Drawing.Point(50,120);
            //series1.Color = Color.Blue;
            ////chart1.Text = "ceshi";
            ////chart1.Titles[0].Text = "fff";
            //chart1.Series.Add(series1);
            ////这一句很重要,缺少的话绘图区域将显示空白
            ////chart1.SizeChanged += new System.EventHandler(DoSizeChanged);
            ////chart1.AllowDrop = true;
            //chart1.BackColor = Color.FromArgb(243, 223, 193);

            ////设置chart背景颜色
            //chartArea1.BackColor = Color.FromArgb(243, 223, 193);

            ////设置c绘图区域背景颜色
            //series1.BorderWidth = 2;
            //series1.IsValueShownAsLabel = true;

            ////是否显示Y的值

            ////this.groupBox9.Controls.Add(chart1);
            //this.panel1.Controls.Add(chart1);
            //chart1.Visible = true;
            ////this.label10.Visible = true;
            ////this.label10.Text = "【" + tn.Name + "】图";
            //chart1.Titles.Add("【" + chart1.Name + "】图");
            ////为Chart1添加标题
            //chartArea1.AxisX.IsMarginVisible = true;

            ////是否显示X轴两端的空白
#endregion

其中注释的部分能实现等分X,Y轴等功能。

自行定义坐标轴箭头大小和修改Y轴的不等间距,代码如下:

private void Chart1_PrePaint_1(object sender, ChartPaintEventArgs e)
        {

            if (e.ChartElement.ToString().StartsWith("ChartArea-"))
            {
                // 获取坐标轴终点
                ChartArea CA = Chart1.ChartAreas[0];
                float xx = (float)CA.AxisX.ValueToPixelPosition(CA.AxisX.Maximum) + 20;//+20将坐标轴箭头右移
                float xy = (float)CA.AxisY.ValueToPixelPosition(CA.AxisY.Crossing);
                float yx = (float)CA.AxisX.ValueToPixelPosition(CA.AxisX.Crossing);
                float yy = (float)CA.AxisY.ValueToPixelPosition(CA.AxisY.Maximum) - 10;//-20将坐标轴箭头上移
                Pen black = new Pen(Color.Black,(float) 0.05);
                e.ChartGraphics.Graphics.DrawLine(black, xx, xy, xx - 20, xy);//增加x轴长度
                e.ChartGraphics.Graphics.DrawLine(black, yx, yy + 10, yx, yy);//增加y轴长度

                #region 绘制不等间隔的Y轴
                e.Chart.ChartAreas[0].AxisY.IsLabelAutoFit = false;
                e.Chart.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
                e.Chart.ChartAreas[0].AxisY.MajorTickMark.Enabled = false;
                e.Chart.ChartAreas[0].AxisY.LabelStyle.ForeColor = System.Drawing.Color.Transparent; 
               
                StripLine sl1 = new StripLine
                {
                    BackColor = Color.Black, //线条黑色
                    IntervalOffset = 20,//显示在Y轴值=20的地方
                    StripWidth = 0.1//线宽
                };
                e.Chart.ChartAreas[0].AxisY.StripLines.Add(sl1);//把它加到AxisY裡去
                //e.Chart.ChartAreas[0].AxisY.StripLines.Add(1)
                Font font = new Font("宋体", 10);
                e.ChartGraphics.Graphics.DrawString("北京", font, new SolidBrush(Color.Red), 80, 150);//可以绘制标签

                StripLine sl2 = new StripLine
                {
                    BackColor = Color.Black, //格線黑色
                    IntervalOffset = 35,//顯示在Y軸值=60的地方
                    StripWidth = 0.1,//線寬
                    //Text = "中北",
                    //TextAlignment = StringAlignment.Near,
                    //TextLineAlignment = StringAlignment.Center,
                };
                e.Chart.ChartAreas[0].AxisY.StripLines.Add(sl2);//
                #endregion

                //一个简单的箭头几何形状
                int arrowSize = 12;//坐标轴尺寸
                Point[] arrowPoints = new Point[3]   { new Point(-arrowSize, -arrowSize / 2),
                new Point(-arrowSize, arrowSize / 2), Point.Empty };

                // draw the two arrows by moving and/or rotating the graphics object:
                e.ChartGraphics.Graphics.TranslateTransform(xx + arrowSize, xy);
                e.ChartGraphics.Graphics.FillPolygon(Brushes.Black, arrowPoints);
                e.ChartGraphics.Graphics.TranslateTransform(yx - xx - arrowSize, yy - xy - arrowSize);
                e.ChartGraphics.Graphics.RotateTransform(-90);
                e.ChartGraphics.Graphics.FillPolygon(Brushes.Black, arrowPoints);
                e.ChartGraphics.Graphics.ResetTransform();
            }
        }
        #endregion

保存图片功能代码如下:

//保存MSchart图
        string fileName ="1";
        private void 保存SToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string saveFileName = "";
            SaveFileDialog saveDialog = new SaveFileDialog
            {
                FileName = fileName//saveDialog.FileName//fileName
            };
            saveFileName = saveDialog.FileName;

            saveDialog.Filter = "Bitmap (*.bmp)|*.bmp|JPEG (*.jpg)|*.jpg|EMF (*.emf)|*.emf|PNG (*.png)|*.png|SVG (*.svg)|*.svg|GIF (*.gif)|*.gif|TIFF (*.tif)|*.tif";
            saveDialog.FilterIndex = 2;
            saveDialog.RestoreDirectory = true;

            // Set image file format
            if (saveDialog.ShowDialog() == DialogResult.OK)
            {
                ChartImageFormat format = ChartImageFormat.Bmp;

                if (saveDialog.FileName.EndsWith("bmp"))
                {
                    format = ChartImageFormat.Bmp;
                }
                else if (saveDialog.FileName.EndsWith("jpg"))
                {
                    format = ChartImageFormat.Jpeg;
                }
                else if (saveDialog.FileName.EndsWith("emf"))
                {
                    format = ChartImageFormat.Emf;
                }
                else if (saveDialog.FileName.EndsWith("gif"))
                {
                    format = ChartImageFormat.Gif;
                }
                else if (saveDialog.FileName.EndsWith("png"))
                {
                    format = ChartImageFormat.Png;
                }
                else if (saveDialog.FileName.EndsWith("tif"))
                {
                    format = ChartImageFormat.Tiff;
                }

                // Save image
                Chart1.SaveImage(saveDialog.FileName, format);
            }

至此,介绍完了三个主要功能。感谢以下博主的帮助:
https://www.cnblogs.com/qiuzhongyang/p/3874006.html
http://blog.sina.com.cn/s/blog_873a233e0100w738.html
(为自己保存资源)https://download.csdn.net/download/weixin_43311110/11107254
没有积分的发邮箱,看见后发码元。

你可能感兴趣的:(C# 调用mschart控件)