OnPaint and GDI+

WinForms draws with GDI+ through a Graphics object, and a control that has something of its own to draw overrides OnPaint. The drawing code cannot run here: System.Drawing.Common is a Windows library, and the container has no display. The arithmetic of the drawing can run, and it is where the bugs are: an off-by-one in a bar, a label outside the plot, a point tested against the wrong rectangle.

OnPaint and PaintEventArgs

Every control raises Paint when it needs to draw itself, and OnPaint is the protected method that raises it. Overriding OnPaint in a derived control is the normal way to add drawing, and the override must call base.OnPaint(e) first so the background and the child controls are drawn.

PaintEventArgs carries two things. Graphics is the drawing surface, clipped to the region that needs repainting. ClipRectangle is that region, and a control that draws a thousand rows reads it to skip the rows outside the damaged area. The Graphics object belongs to the paint cycle: it must not be stored in a field and must not be disposed by the handler. It is created by the framework, passed in, and destroyed after the method returns.

A repaint is asked for, never forced: Invalidate() marks the control and returns, and the next idle moment of the message loop raises Paint. Invalidate(rectangle) marks a part, Update() processes the pending paint immediately, and Refresh() does both. Calling Invalidate from a loop is cheap; calling Refresh from a loop repaints a thousand times.

A bar chart in OnPaint

The form draws six bars from an array, with the plot area recomputed from ClientSize on every paint, so a resize is just a new paint. Built and not run:

using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; internal static class Program { [STAThread] private static void Main() { ApplicationConfiguration.Initialize(); Application.Run(new ChartForm()); } } internal sealed class ChartForm : Form { private readonly int[] _values = { 40, 90, 55, 120, 75, 30 }; public ChartForm() { Text = "OnPaint"; ClientSize = new Size(440, 240); DoubleBuffered = true; Resize += (sender, e) => Invalidate(); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); var g = e.Graphics; g.SmoothingMode = SmoothingMode.AntiAlias; g.Clear(Color.White); var plot = new Rectangle(40, 24, ClientSize.Width - 64, ClientSize.Height - 64); using var axis = new Pen(Color.Gray); using var bar = new SolidBrush(Color.SteelBlue); using var label = new SolidBrush(Color.Black); using var caption = new Font("Segoe UI", 8F); g.DrawLine(axis, plot.Left, plot.Top, plot.Left, plot.Bottom); g.DrawLine(axis, plot.Left, plot.Bottom, plot.Right, plot.Bottom); var slot = plot.Width / _values.Length; for (var i = 0; i < _values.Length; i++) { var height = plot.Height * _values[i] / 120; var rectangle = new Rectangle(plot.Left + (i * slot) + 8, plot.Bottom - height, slot - 16, height); g.FillRectangle(bar, rectangle); g.DrawString(_values[i].ToString(), caption, label, rectangle.Left, rectangle.Top - 16); } } }

dotnet build app.csproj

Build succeeded.
    0 Warning(s)
    0 Error(s)

The listing is built and not run. Four things in it are worth taking to any paint code. Clear is called because the form's background is not reliable under a custom paint; without it the old bars show through. SmoothingMode applies to the whole Graphics and is a per-paint setting. The font is created once per paint, which is a small allocation a form can avoid by holding it in a field, and the pen and brushes are in using declarations so they are disposed at the end of the method. And every coordinate is an int computed from ClientSize, so the chart follows the window without a layout engine.

Pen, Brush and the using rule

GDI+ objects are handles to native resources. A Pen, a Brush, a Font and a Bitmap each allocate one, and the garbage collector does not know how much of them the system can afford. The rule is the one from any IDisposable: create, use, dispose, preferably with a using declaration.

The colours are System.Drawing.Color values: named colours, FromArgb for alpha and RGB, and FromKnownColor for a system colour. A hard-coded colour ignores the high-contrast theme, which is an accessibility bug; SystemColors is the set that follows the theme.

The arithmetic that runs

The same layout with no Graphics: Rectangle, Point and integer division, which are plain structs and run on any platform. The program prints every bar and whether it fits the plot. It was built and run here:

using System; using System.Drawing; Console.WriteLine("bar geometry for a 400 x 200 chart"); var plot = new Rectangle(40, 24, 340, 160); var values = new[] { 40, 90, 55, 120, 75, 30 }; var slot = plot.Width / values.Length; for (var i = 0; i < values.Length; i++) { var height = plot.Height * values[i] / 120; var bar = new Rectangle(plot.Left + (i * slot) + 8, plot.Bottom - height, slot - 16, height); var inside = plot.Contains(bar) ? "inside" : "clipped"; Console.WriteLine($"bar {i + 1}: {bar}, height {height}, {inside}"); } Console.WriteLine($"plot: {plot}, slot {slot}, right {plot.Right}, bottom {plot.Bottom}"); var hover = new Point(120, 100); Console.WriteLine($"the point {hover} is in the plot: {plot.Contains(hover)}");

dotnet run

bar geometry for a 400 x 200 chart
bar 1: {X=48,Y=131,Width=40,Height=53}, height 53, inside
bar 2: {X=104,Y=64,Width=40,Height=120}, height 120, inside
bar 3: {X=160,Y=111,Width=40,Height=73}, height 73, inside
bar 4: {X=216,Y=24,Width=40,Height=160}, height 160, inside
bar 5: {X=272,Y=84,Width=40,Height=100}, height 100, inside
bar 6: {X=328,Y=144,Width=40,Height=40}, height 40, inside
plot: {X=40,Y=24,Width=340,Height=160}, slot 56, right 380, bottom 184
the point {X=120,Y=100} is in the plot: True

The output is the real run, and it is the arithmetic a paint handler gets wrong. The plot is 340 wide with six bars, so the slot is 56 and the integer division drops the remainder; the last bar ends at x = 368 and the plot at 380, which leaves a margin on the right. The bar for 40 is 53 pixels high because 160 * 40 / 120 truncates 53.33, and the tallest bar is exactly the plot height. plot.Contains(bar) is a rectangle test, which is the same call the hit testing of lesson 065 makes with a point.

Rectangle has four properties worth knowing: Left, Top, Right and Bottom, where Right and Bottom are exclusive. A rectangle at x = 0 with width 10 has Right = 10, and a point at x = 10 is outside it. That single rule explains most off-by-one errors in a chart.

Flicker and double buffering

A control that clears and redraws on every paint flickers, because the clear is visible before the redraw. The fix is double buffering: the paint goes to an off-screen bitmap and the finished bitmap is copied to the screen in one operation. WinForms has a property for it, and a form should set it:

DoubleBuffered = true;

For a custom Control the property is protected, so the constructor of the control sets it with SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true). AllPaintingInWmPaint is the second half: it suppresses the separate background paint and sends everything through OnPaint, which is what makes the buffer work. A control with a transparent background sets ControlStyles.SupportsTransparentBackColor and takes the cost.

Double buffering does not make a slow paint fast; it hides the intermediate states. A paint that takes 200 milliseconds still freezes the window for 200 milliseconds, twice if the control is resized continuously. The real fix is to draw less: clip to the damage rectangle, cache the expensive text layout, and precompute the geometry instead of recomputing it per pixel.

Exercises

  1. Change the chart to horizontal bars and run the geometry program with the new formulas.
  2. Add a bar for a value of 150 to the geometry program and explain what the Contains test reports and why.
  3. Cache the Font in a field, dispose it in Dispose(bool) and explain what the per-paint allocation cost.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which method does a control override to draw itself?

    Answer

    OnPaint

    It is protected and raises the Paint event after it.

  2. What must the OnPaint override do first?

    Answer

    Call base.OnPaint(e)

    The base paint draws the background and the children.

  3. Who owns the Graphics object in PaintEventArgs?

    Answer

    The framework: pass it, use it, do not dispose it

    A disposed Graphics corrupts the paint cycle.

  4. What does Invalidate do?

    Answer

    Marks the control for a repaint at the next idle moment

    Update and Refresh are the synchronous variants.

  5. How high is the bar for the value 40 in the run?

    Answer

    53

    160 * 40 / 120 truncates 53.33.

  6. What is Rectangle.Right for a rectangle at 0 with width 10?

    Answer

    10, and it is exclusive

    Right is Left plus Width, and the right edge is not inside.

  7. Which brush fills with one colour?

    Answer

    SolidBrush

    The chart uses it for the bars.

  8. Which object is created per paint in the chart and could be cached?

    Answer

    The Font

    A font is a GDI+ handle and belongs to the form.

  9. What does DoubleBuffered prevent?

    Answer

    The flicker of a clear followed by a redraw

    The finished frame is copied in one operation.

  10. Why does the geometry program run on Linux?

    Answer

    Point, Size and Rectangle are plain structs, not GDI+ handles

    The drawing needs Windows; the arithmetic does not.

Every listing on this page was built with the .NET SDK 10.0.303 for net10.0-windows against the targeting pack Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed, in a Docker container on Alpine Linux 3.24.3 (x86_64). The programs were built, not run on Linux: WinForms needs Windows. The logic that draws nothing was also run headless on the same machine, and its output is the run output printed below each of those programs.

Article author: Arthur Isaev