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 forSystem.Drawing
for more information and what you can do about it.
Code
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;
gfx.Clear(Color.Navy);
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);
}
bmp.Save("demo.png");
Output

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:
System.Drawing.Image
System.Drawing.Bitmap
System.Drawing.Graphics
System.Drawing.Pen
System.Drawing.Brush
System.Drawing.Font
System.Drawing.FontFamily
System.Drawing.StringFormat
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).
Resources
-
Source code: projects/system-drawing/quickstart-console/