Resources for visualizing data using C# and the .NET platform
How to use System.Drawing to create graphics in a C# console application

This example .NET Console application uses System.Drawing to draw 10,000 random lines on a dark blue background and save the output as a PNG file.

⚠️ Warning: System.Drawing.Common now only supports Windows!
See Cross-Platform Support for System.Drawing for more information and what you can do about it.


This example uses .NET 6 and version 4.* of the System.Drawing.Common package.

using System.Drawing;

using Bitmap bmp = new(600, 400);
using Graphics gfx = Graphics.FromImage(bmp);
gfx.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;


Random rand = new(0);
using Pen pen = new(Color.White);
for (int i = 0; i < 10_000; i++)
    pen.Color = Color.FromArgb(rand.Next());
    Point pt1 = new(rand.Next(bmp.Width), rand.Next(bmp.Height));
    Point pt2 = new(rand.Next(bmp.Width), rand.Next(bmp.Height));
    gfx.DrawLine(pen, pt1, pt2);



Respect IDisposable

Many System.Drawing objects inherit from IDisposable and it is critical that they are disposed of properly to avoid memory issues. This means calling Dispose() after you’re done using an object, or better yet throwing its instantiation inside a using statement.

💡 Deep Dive: Read Microsoft’s documentation about using objects that implement IDisposable

Take care to properly dispose of these common System.Drawing objects:

Anti-Aliased Graphics and Text

Anti-aliasing is OFF by default. Enabling anti-aliasing significantly slows render time but produces superior images when drawing angled lines and edges. Anti-aliasing can be enabled separately for shapes and text.

// Configure anti-aliasing mode for graphics
gfx.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
gfx.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;

// Configure anti-aliasing mode for text
gfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit;
gfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
gfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;

ClearType typically looks the best, but when drawn on a transparent background it looks poor (because reasons).