24
Lesson 24 of 35 · WinForms

Graphics & GDI+

GDI+ is .NET's 2D drawing API. Every WinForms control exposes a Paint event where you receive a Graphics object to draw lines, shapes, text, and images.

Handling the Paint Event

Subscribe to the form's or panel's Paint event. Never call drawing code outside of a Paint handler—call Invalidate() to request a repaint.

Paint event Paint.cs
private void panel1_Paint(object sender, PaintEventArgs e)
{
    Graphics g = e.Graphics;
    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

    // Draw filled rectangle
    g.FillRectangle(Brushes.SteelBlue, 20, 20, 100, 60);

    // Draw ellipse outline
    using var pen = new Pen(Color.Orange, 3);
    g.DrawEllipse(pen, 140, 20, 100, 60);

    // Draw text
    using var font = new Font("Segoe UI", 14, FontStyle.Bold);
    g.DrawString("GDI+", font, Brushes.White, 20, 100);
}

Drawing Shapes

The Graphics class provides methods for every primitive: DrawLine, DrawRectangle, FillRectangle, DrawEllipse, FillEllipse, DrawPolygon, FillPolygon, and DrawPath.

Shapes Shapes.cs
private void DrawShapes(Graphics g)
{
    // Gradient brush
    var grad = new System.Drawing.Drawing2D.LinearGradientBrush(
        new Rectangle(0, 0, 200, 200),
        Color.DodgerBlue, Color.MediumOrchid,
        System.Drawing.Drawing2D.LinearGradientMode.Diagonal);

    g.FillEllipse(grad, 50, 50, 200, 200);

    // Polygon (star points simplified)
    Point[] tri = { new(300, 50), new(350, 150), new(250, 150) };
    g.FillPolygon(Brushes.Tomato, tri);
}