在MajorGrid上放几个月,在MinorGrid上放几天(范围条形图)

时间:2019-03-05 11:44:43

标签: c# charts

我有这个甘特图:

Chart image

我想在MajorGrid上显示月份,在MinorGrid上显示几天,我尝试更改时间间隔,但没有任何改变

编辑:我想要的是这样的东西:

1 个答案:

答案 0 :(得分:1)

您可以添加两行自定义标签,如下所示:

ay.LabelStyle.Angle = 0;
ay.IsLabelAutoFit = true;
DateTime d1 = DateTime.FromOADate(ay.Minimum);
DateTime d2 = DateTime.FromOADate(ay.Maximum);
int dc = (int)(d2 - d1).TotalDays;
//double dspace = d2.ToOADate() - d1.ToOADate();  // we need a suitable number later (*)
dspace = 10;    // seems to work better when zooming in..
for (int i = 0; i < dc; i++)
{
    DateTime dt = d1.AddDays(i);
    double dd = dt.ToOADate();
    CustomLabel cl = new CustomLabel();
    cl.Text = dt.Day + "";
    cl.FromPosition = dd - dspace;  //(*)
    cl.ToPosition = dd + dspace;   //(*)
    cl.RowIndex = 0;              // 1st row of labels

    ay.CustomLabels.Add(cl);

    if (dt.Day == 1)  // place month name at the 1st day
    {
        cl = new CustomLabel();
        string month = d1.AddDays(i).ToString("MMMM");
        cl.Text = month;
        cl.FromPosition = dd - dspace;  //(*)
        cl.ToPosition = dd + dspace;   //(*)
        cl.RowIndex = 1;              // 2nd row
        ay.CustomLabels.Add(cl);
    }
}

其中Axis ay = ca.AxisY;var ca = chart1.ChartAreas[0];

结果:

enter image description here

在PrePaint事件中绘制了黄色矩形。示例:

private void chart1_PrePaint(object sender, ChartPaintEventArgs e)
{
    Series s = chart1.Series[0];
    if (s.Points.Count <= 0) return;
    Graphics g = e.ChartGraphics.Graphics;

    var ca = chart1.ChartAreas[0];
    Axis ay = ca.AxisY;
    DateTime d1 = DateTime.FromOADate(ay.Minimum);
    DateTime d2 = DateTime.FromOADate(ay.Maximum);

    int x1 = (int)ay.ValueToPixelPosition(ay.Minimum);
    int x2 = (int)ay.ValueToPixelPosition(ay.Maximum);
    int y = (int)ca.AxisX.ValueToPixelPosition(ca.AxisX.Minimum);
    using (SolidBrush b = new SolidBrush(Color.FromArgb(11, 222, 222, 111)))
        g.FillRectangle(b, x1, y, x2 - x1, 60);  // 60 pixels large, calculate what you need!
}

我不得不承认我不知所措。也许(更多)涉及到的绘画代码很接近您的示例。