50老人摸索了很多天搞了一个自用了K线图,用C# +Mschart,说一下代码过程中的几个遇到的问题。
mschart 用法主要在Series,一是数据源要配准确,不然显示不出图,然后要搞明白坐标轴和刻度。还有很多想法由于水平有限不会实现。
由于一些网友需要,我把主要代码放上来,网友只要配置好数据就可以了。
// 创建图像
public void CreateChart()
{
//设置类型
//chart1.Series["Series1"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Candlestick;
//设置Y轴最大值,其中数值需要动态调整
//chart1.ChartAreas[0].AxisY.Maximum = System.Convert.ToDouble(20);
//设置Y轴最小值
//chart1.ChartAreas[0].AxisY.Minimum = System.Convert.ToDouble(5);
//网格线颜色Major为大刻度,Minor为小刻
chart1.ChartAreas[0].AxisX.MajorGrid.LineColor = System.Drawing.Color.LightGray;
chart1.ChartAreas[0].AxisY.MajorGrid.LineColor = System.Drawing.Color.LightGray;
chart1.ChartAreas[0].AxisX.MinorGrid.LineColor = System.Drawing.Color.LightGray;
chart1.ChartAreas[0].AxisX.MajorGrid.Enabled = false; //不显示X轴网格
chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = false; //不显示Y轴网格
//刻度数值角度
//chart1.ChartAreas[0].AxisX.LabelStyle.Angle = 45;
//加载数据
for(int i=0;i<300;i++)
{
//int currentIndex = chart1.Series["Candle"].Points.Count;
//Console.WriteLine(currentIndex);
chart1.Series["Candle"].Points.AddXY(pdate[i], phigh[i]);
//chart1.Series["Candle"].Points[currentIndex].YValues[0] = System.Convert.ToDouble(phigh[i]);
chart1.Series["Candle"].Points[i].YValues[1] = System.Convert.ToDouble(plow[i]);
chart1.Series["Candle"].Points[i].YValues[2] = System.Convert.ToDouble(popen[i]);
chart1.Series["Candle"].Points[i].YValues[3] = System.Convert.ToDouble(pclose[i]);
//设置上下小线的颜色
if (pclose[i] < popen[i])
{
chart1.Series["Candle"].Points[i].Color = Color.Cyan;
}
else {
chart1.Series["Candle"].Points[i].Color = Color.Red;
}
//chart1.Series["Candle"].Points[currentIndex].AxisLabel = pdate[i];
//chart1.Series["Candle"].Points[currentIndex].Color = Color.Black;
}
//for (int i = 0; i < records.Count; i++)
//{
// s.Points.AddXY(records[i].CurrentDate, records[i].HighValue);
// s.Points[i].YValues[1] = records[i].LowValue;
// s.Points[i].YValues[2] = records[i].OpenValue;
// s.Points[i].YValues[3] = records[i].CloseValue;
// }
//chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.NotSet;
//chart1.ChartAreas[0].AxisX.Interval = 1;
chart1.Series["Candle"].CustomProperties = "PriceDownColor=Cyan,PriceUpColor=Red";
chart1.ChartAreas[0].CursorX.IsUserEnabled = true;
chart1.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
chart1.ChartAreas[0].AxisX.ScaleView.Zoomable = true;//允许X轴方向缩放
chart1.ChartAreas[0].AxisY.IsStartedFromZero = false; //此为解决Y轴自适应,用这句不用设置最大最小值
// 设置自动放大与缩小的最小量
chart1.ChartAreas[0].AxisX.ScaleView.SmallScrollSize = double.NaN;
chart1.ChartAreas[0].AxisX.ScaleView.SmallScrollMinSize = 1;
}
private void label1_Click(object sender, EventArgs e)
{
chart1.ChartAreas[0].AxisX.ScaleView.ZoomReset();//X方向恢复原样
//chart1.ChartAreas[0].AxisY.ScaleView.ZoomReset();
}
private void label2_Click(object sender, EventArgs e)
{
chart1.ChartAreas[0].AxisX.ScaleView.Size -= 4;
}