• DR-IT Software
  • Products
  • Documentation
  • Product page
  • Examples
  • API reference
  • Support

Rendering and graphics state

A Graphics object carries state that affects everything drawn after it is set: the smoothing mode, the clip, the transform and the page units. Set it deliberately, and save and restore state around local changes so it does not leak into later drawing.

Antialiasing

Two circles, the left drawn without smoothing and the right with antialiasing

Draws the same circle twice: the left with SmoothingMode.None, the right with SmoothingMode.AntiAlias.

At normal size the difference is subtle, so the example also enlarges a 40 × 40 pixel patch of each circle's edge eight times (nearest-neighbour, so the pixels stay square). On the left every pixel is fully inked or empty, which makes the staircase; on the right the edge pixels are blended with the background in intermediate shades.

The edge of each circle enlarged eight times: stair-stepped on the left, blended on the right

SmoothingMode applies to the calls made after it is set, so mixing modes in one drawing is just a matter of ordering. For most drawings, set AntiAlias once at the top. Gradient and texture brushes give the same colours in both modes.

internal static void RenderingAntialiasing(ExampleContext context)
{
    using var bitmap = ExampleSupport.NewCanvas(720, 420, Color.White);
    using var graphics = Graphics.FromImage(bitmap);
    using var pen = new Pen(Color.DarkBlue, 3);
    graphics.SmoothingMode = SmoothingMode.None;
    graphics.DrawEllipse(pen, new RectangleF(45, 50, 260, 260));
    graphics.SmoothingMode = SmoothingMode.AntiAlias;
    graphics.DrawEllipse(pen, new RectangleF(410, 50, 260, 260));
    ExampleSupport.Save(bitmap, context, "Antialiasing-antialiasing.png", ImageFormat.Png);

    // At 1:1 the difference is subtle, so also enlarge the same 40 x 40 pixel patch of each
    // circle's edge eight times, without smoothing, to make the individual pixels visible.
    using var zoomed = ExampleSupport.NewCanvas(680, 340, Color.White);
    using var zoom = Graphics.FromImage(zoomed);
    zoom.InterpolationMode = InterpolationMode.NearestNeighbor;
    zoom.DrawImage(bitmap, new RectangleF(10, 10, 320, 320), new RectangleF(30, 150, 40, 40), GraphicsUnit.Pixel);
    zoom.DrawImage(bitmap, new RectangleF(350, 10, 320, 320), new RectangleF(395, 150, 40, 40), GraphicsUnit.Pixel);
    ExampleSupport.Save(zoomed, context, "Antialiasing-zoomed-edges.png", ImageFormat.Png);
}

AlphaBlending

Red and yellow translucent ellipses overlapping on a dark-blue rectangle

Draws two ellipses with alpha 150 (of 255) over an opaque dark-blue rectangle.

A translucent source colour is mixed with whatever is already on the canvas, so each ellipse picks up the blue behind it, and where they overlap the result depends on draw order (yellow is drawn after red, so it sits on top). Blending happens as you draw; changing the background afterwards does not re-blend.

internal static void RenderingAlphaBlending(ExampleContext context)
{
    using var bitmap = ExampleSupport.NewCanvas(720, 420, Color.White);
    using var graphics = Graphics.FromImage(bitmap);
    using var back = new SolidBrush(Color.DarkBlue);
    using var red = new SolidBrush(Color.FromArgb(150, 220, 45, 45));
    using var yellow = new SolidBrush(Color.FromArgb(150, 245, 200, 50));
    graphics.FillRectangle(back, 65, 65, 590, 290);
    graphics.FillEllipse(red, new RectangleF(130, 100, 260, 220));
    graphics.FillEllipse(yellow, new RectangleF(330, 100, 260, 220));
    ExampleSupport.Save(bitmap, context, "AlphaBlending-alpha-blending.png", ImageFormat.Png);
}

Clipping

Green vertical bars visible only inside a rectangle, with a dark outline

Restricts drawing to a rectangle with SetClip, draws bars that run far past it, then calls ResetClip and outlines the boundary.

Only the part of each bar inside the clip is painted. ResetClip removes the restriction altogether; it does not go back to an earlier clip. When you need to return to a previous clip, use saved state instead (see GraphicsState).

internal static void RenderingClipping(ExampleContext context)
{
    using var bitmap = ExampleSupport.NewCanvas(720, 420, Color.White);
    using var graphics = Graphics.FromImage(bitmap);
    using var brush = new SolidBrush(Color.FromArgb(210, 50, 150, 100));
    graphics.SetClip(new Rectangle(105, 65, 510, 290), CombineMode.Replace);
    for (int x = -400; x < 900; x += 45)
        graphics.FillRectangle(brush, x, 30, 25, 370);
    graphics.ResetClip();
    using var outline = new Pen(Color.DarkSlateGray, 4);
    graphics.DrawRectangle(outline, 105, 65, 510, 290);
    ExampleSupport.Save(bitmap, context, "Clipping-clipping.png", ImageFormat.Png);
}

Transforms

A tilted, stretched orange ellipse with a blue outline

Draws an ellipse after TranslateTransform, RotateTransform and ScaleTransform.

The Graphics transform methods prepend by default, so the last one called is applied to the shape first: the ellipse is scaled, then rotated, then moved to the centre of the canvas. Call them in the opposite order and you get a different picture. The transform affects every later draw call, including pen width, until you reset it or restore saved state.

internal static void RenderingTransforms(ExampleContext context)
{
    using var bitmap = ExampleSupport.NewCanvas(720, 420, Color.White);
    using var graphics = Graphics.FromImage(bitmap);
    using var pen = new Pen(Color.DarkBlue, 6);
    using var brush = new SolidBrush(Color.FromArgb(170, 240, 160, 40));
    graphics.TranslateTransform(360, 210);
    graphics.RotateTransform(-20);
    graphics.ScaleTransform(1.3f, 0.8f);
    graphics.FillEllipse(brush, new RectangleF(-150, -90, 300, 180));
    graphics.DrawEllipse(pen, new RectangleF(-150, -90, 300, 180));
    ExampleSupport.Save(bitmap, context, "Transforms-transforms.png", ImageFormat.Png);
}

CombinedClips

A single translucent blue rectangle: the intersection of two clip rectangles

Sets one clip rectangle, intersects it with a second using IntersectClip, and fills the whole canvas.

Although the fill covers all 720 × 360 pixels, only the area inside both clip rectangles is painted. IntersectClip narrows the current clip; SetClip(rect, CombineMode.Replace) would replace it.

Two clip rectangles A and B and their intersection

internal static void CombinedClips(ExampleContext c)
{
    using var bitmap = ExampleSupport.NewCanvas(720, 360, Color.White);
    using var g = Graphics.FromImage(bitmap);
    using var brush = new SolidBrush(Color.FromArgb(190, 80, 130, 210));
    g.SetClip(new Rectangle(70, 60, 450, 230), CombineMode.Replace);
    g.IntersectClip(new Rectangle(250, 110, 400, 190));
    g.FillRectangle(brush, new RectangleF(0, 0, 720, 360));
    g.ResetClip();
    ExampleSupport.Save(bitmap, c, "CombinedClips-combined-clips.png", ImageFormat.Png);
}

MatrixTransforms

The original triangle, two transformed copies, and the inverse-restored triangle

Transforms the three corners of a triangle with a Matrix, in both orders, and then maps one result back with the inverse.

  • Blue – the original triangle at the top left.
  • Orange – Translate then Rotate with the default MatrixOrder.Prepend: the points are rotated about the origin first, then moved.
  • Green – the same two operations with MatrixOrder.Append on the rotation: the points are moved first, then rotated about the origin, so the triangle swings away to a different place.
  • Red, dashed – the orange points passed through Invert() and transformed again. They land exactly on the blue triangle (to rounding).

Matrix order is the usual source of "my shape is in the wrong place" bugs. Only an invertible matrix has an inverse; check IsInvertible for matrices you did not build yourself.

internal static void MatrixOrderAndInverse(ExampleContext c)
{
    using var bitmap = ExampleSupport.NewCanvas(720, 420, Color.White);
    using var g = Graphics.FromImage(bitmap);
    var points = new[] { new PointF(40, 40), new PointF(160, 40), new PointF(40, 140) };

    // Prepend (the default): the points are rotated first, then translated.
    using var rotateThenMove = new Matrix();
    rotateThenMove.Translate(300, 120);
    rotateThenMove.Rotate(30);

    // Append: the points are translated first, then rotated about the origin.
    using var moveThenRotate = new Matrix();
    moveThenRotate.Translate(300, 120);
    moveThenRotate.Rotate(30, MatrixOrder.Append);

    var first = (PointF[])points.Clone();
    rotateThenMove.TransformPoints(first);
    var second = (PointF[])points.Clone();
    moveThenRotate.TransformPoints(second);

    // The inverse maps the first result back onto the original points.
    var restored = (PointF[])first.Clone();
    rotateThenMove.Invert();
    rotateThenMove.TransformPoints(restored);

    using var original = new Pen(Color.DarkBlue, 4);
    using var firstPen = new Pen(Color.DarkOrange, 4);
    using var secondPen = new Pen(Color.DarkGreen, 4);
    using var restoredPen = new Pen(Color.Red, 2) { DashStyle = DashStyle.Dash };
    g.DrawPolygon(original, points);
    g.DrawPolygon(firstPen, first);
    g.DrawPolygon(secondPen, second);
    g.DrawPolygon(restoredPen, restored);
    Console.WriteLine($"  inverse restored first point: {restored[0].X:0.0},{restored[0].Y:0.0}");
    ExampleSupport.Save(bitmap, c, "MatrixTransforms-matrix-order-inverse.png", ImageFormat.Png);
}

GraphicsState

A blue rotated rectangle and an orange upright rectangle

Saves the graphics state, rotates and translates to draw one rectangle, restores the state, and draws a second.

Save returns a GraphicsState that Restore takes back: the transform and the clip return to what they were. The blue rectangle is drawn around the rotated origin; after Restore, the orange one is placed with plain canvas coordinates. This is the safe way to apply a transform to part of a drawing.

internal static void SaveRestoreState(ExampleContext c)
{
    using var bitmap = ExampleSupport.NewCanvas(720, 360, Color.White);
    using var g = Graphics.FromImage(bitmap);
    using var pen = new Pen(Color.DarkBlue, 5);
    var state = g.Save();
    g.TranslateTransform(350, 170);
    g.RotateTransform(25);
    g.DrawRectangle(pen, new RectangleF(-120, -70, 240, 140));
    g.Restore(state);
    g.DrawRectangle(new Pen(Color.DarkOrange, 5), new RectangleF(40, 40, 200, 120));
    ExampleSupport.Save(bitmap, c, "GraphicsState-save-restore-state.png", ImageFormat.Png);
}

PageUnits

A green rectangle and its caption, positioned in millimetres

Sets PageUnit to GraphicsUnit.Millimeter and draws an 80 × 45 rectangle and a caption using millimetre coordinates.

With a page unit set, the coordinates you pass to drawing methods are in that unit. At the bitmap's 96 dpi, 80 mm is about 302 pixels, so the rectangle covers roughly 40 % of the 760-pixel width. Font sizes are not affected: they stay in the unit of the Font. The page settings the example recorded:

PageUnit=Millimeter; PageScale=1

Physical size on a printout or a screen also depends on the resolution of the output device, so treat millimetres here as a coordinate system, not a guarantee of real-world size.

internal static void UnitsAndPageCoordinates(ExampleContext c)
{
    using var bitmap = ExampleSupport.NewCanvas(760, 400, Color.White);
    using var g = Graphics.FromImage(bitmap);
    using var pen = new Pen(Color.DarkGreen, 3);
    using var label = new DrawingFont(DRIT.Drawing.Text.FontFamily.GenericSansSerif, 16);
    using var text = new SolidBrush(Color.Black);
    g.PageUnit = GraphicsUnit.Millimeter;
    g.PageScale = 1f;
    g.DrawRectangle(pen, new RectangleF(10, 10, 80, 45));
    g.DrawString("80 × 45 mm page-unit rectangle", label, text, 12, 60);
    File.WriteAllText(c.Path("PageUnits-units.txt"), $"PageUnit={g.PageUnit}; PageScale={g.PageScale}");
    ExampleSupport.Save(bitmap, c, "PageUnits-units-page-coordinates.png", ImageFormat.Png);
}
  • Improve this Doc
Back to top

DR-IT Software documentation

DR-IT Software · Products · Documentation index · Product page · Downloads · Support · Licensing

Generated by DocFX