這是不可能的GridLines
因爲它們將總是在固定Interval
間隔繪製。這是一種通過在xxxPaint
事件繪製線周圍工作的一個例子..
首先聲明我們要爲GridLines
停止值的列表:
List<double> stops = new List<double>();
然後,我們準備的圖表:
AddPoints();
ChartArea ca = chart1.ChartAreas[0];
ca.AxisX.Minimum = 0; // optional
ca.AxisX.MajorGrid.Enabled = false;
ca.AxisX.MajorTickMark.Enabled = false;
ca.AxisX.LabelStyle.Enabled = false;
stops.AddRange(new[] { 0, 15, 45, 50.5, 65, 90, 100 });
請注意,我已經加入一個額外的價值(50.5
),以展示我們如何可以借鑑GridLines
即使不DataPoints
!
然後我們編寫了PostPaint
事件:
private void chart1_PostPaint(object sender, ChartPaintEventArgs e)
{
Graphics g = e.ChartGraphics.Graphics;
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
ChartArea ca = chart1.ChartAreas[0];
Font font = ca.AxisX.LabelStyle.Font;
Color col = ca.AxisX.MajorGrid.LineColor;
int padding = 10; // pad the labels from the axis
int y0 = (int)ca.AxisY.ValueToPixelPosition(ca.AxisY.Minimum);
int y1 = (int)ca.AxisY.ValueToPixelPosition(ca.AxisY.Maximum);
foreach (int sx in stops)
{
int x = (int)ca.AxisX.ValueToPixelPosition(sx);
using (Pen pen = new Pen(col))
g.DrawLine(pen, x, y0, x, y1);
string s = sx + "";
if (ca.AxisX.LabelStyle.Format != "")
s = string.Format(ca.AxisX.LabelStyle.Format, s);
SizeF sz = g.MeasureString(s, font, 999);
g.DrawString(s, font, Brushes.Black, (int)(x - sz.Width/2) , y0 + padding);
}
這是結果:
注意,大多數在PostPaint
事件的代碼只是準備工作;兩個實際的繪圖呼籲線和標籤都是普通GDI+
方法..
請注意,我已經加入DataPoint
標籤在循環每10個點,以顯示我們在哪裏:
chart1.Series[0].Points.AddXY(i, i);
if (i%10 == 0) chart1.Series[0].Points[i].Label = "#VAL/#VALY";
來源
2017-06-04 11:29:39
TaW
謝謝你很多,TaW。 – Viknesh