Graphics Class
The System.Drawing.Graphics class provides methods for drawing objects to a display device. It is the primary class for rendering shapes, images, and text in Windows Forms applications.
Key Features
- Device‑independent drawing primitives (lines, curves, ellipses, etc.)
- High‑quality text rendering with support for GDI+ text options
- Image manipulation and transformation (rotate, scale, translate)
- Clipping, compositing, and anti‑aliasing controls
- Integration with WinForms controls via the
Paintevent
Getting a Graphics Object
// Within a Form or Control
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
// Use g to draw
base.OnPaint(e);
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
// Use g to draw
base.OnPaint(e);
}
Common Methods
| Method | Description |
|---|---|
| DrawLine | Draws a line between two points. |
| DrawRectangle | Draws the outline of a rectangle. |
| FillRectangle | Fills the interior of a rectangle. |
| DrawEllipse | Draws the outline of an ellipse. |
| FillEllipse | Fills the interior of an ellipse. |
| DrawString | Renders text using a specified font and brush. |
| MeasureString | Measures the size of a string before drawing. |
| DrawImage | Draws an image to the graphics surface. |
| Transform | Applies a transformation matrix to subsequent drawing operations. |
| ResetTransform | Resets the world transformation to the identity matrix. |
Examples
Below is a simple example that draws a red circle and some text.
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
using (Pen redPen = new Pen(Color.Red, 2))
{
g.DrawEllipse(redPen, 50, 50, 200, 200);
}
using (Brush brush = new SolidBrush(Color.Blue))
{
g.DrawString("Hello, Graphics!", new Font("Segoe UI", 16), brush, new PointF(80, 260));
}
base.OnPaint(e);
}
{
Graphics g = e.Graphics;
using (Pen redPen = new Pen(Color.Red, 2))
{
g.DrawEllipse(redPen, 50, 50, 200, 200);
}
using (Brush brush = new SolidBrush(Color.Blue))
{
g.DrawString("Hello, Graphics!", new Font("Segoe UI", 16), brush, new PointF(80, 260));
}
base.OnPaint(e);
}