Custom Annotate Your Charts

A few posts back, I described the new Microsoft Chart Controls for the .Net Framework: Chart Demo.   While playing with the controls a bit over the holidays, I was pleasantly surprised to find you can hook into the paint events while the chart is being rendered.

In the code below, I've hooked into the Post Paint event of the chart in the previous demo to add a custom annotation to the chart. Here is what the chart looks like with the date printed and copyright annotation at the bottom:

Custom Annotated Chart

In order to make this happen, you hook into the chart control's PostPaint event:

    <asp:Chart ID="Chart1" runat="server" 
        OnPostPaint="Chart1_PostPaint"    

In the event handler, you are given access to the Graphics object and can draw on the surface of the graph:  

protected void Chart1_PostPaint(object sender, ChartPaintEventArgs e)
{
    if (e.ChartElement is Chart)
    {
        // create text to draw
        String TextToDraw;
        TextToDraw = "Printed: " + DateTime.Now.ToString("MMM d, yyyy @ h:mm tt");
        TextToDraw += " -- Copyright © Steve Wellens";
 
        // get graphics tools
        Graphics g = e.ChartGraphics.Graphics;
        Font DrawFont = System.Drawing.SystemFonts.CaptionFont;
        Brush DrawBrush = Brushes.Black;
 
        // see how big the text will be
        int TxtWidth = (int)g.MeasureString(TextToDraw, DrawFont).Width;
        int TxtHeight = (int)g.MeasureString(TextToDraw, DrawFont).Height;
 
        // where to draw
        int x = 5;  // a few pixels from the left border
 
        int y = (int)e.Chart.Height.Value;
        y = y - TxtHeight - 5; // a few pixels off the bottom
 
        // draw the string        
        g.DrawString(TextToDraw, DrawFont, DrawBrush, x, y);
    }
}

Notes:

In the real world, I would put this in a separate function to be reusable (to keep the demo simple, I left it in the handler).

Several paint events are generated while painting the graph. The text is only drawn when the main chart element is drawn.

To keep the text legible I left an arbitrary 5 pixels between the left side and bottom.

Question:

The chart control has PrePaint events and PostPaint events. I couldn't find any behavioral differences or documentation on the differences. Does anyone know why there are both PrePaint and PostPaint events?

I hope you find this useful.

Steve Wellens

2 Comments

Comments have been disabled for this content.