MAUI Graphics API Reference

Introduction to MAUI Graphics

The .NET MAUI Graphics API provides a powerful and unified way to draw 2D graphics across multiple platforms (iOS, Android, macOS, Windows). It leverages the underlying native graphics capabilities of each platform while offering a consistent C# interface.

This API is ideal for creating custom controls, drawing visualizations, implementing game UIs, or any scenario where precise 2D drawing is required. It integrates seamlessly with XAML and C# code-behind for building rich user interfaces.

Getting Started

To start using the MAUI Graphics API, you'll typically interact with a ICanvas object. This object is provided within the Draw method of custom controls or through handlers.

The fundamental workflow involves:

  1. Obtaining an ICanvas instance.
  2. Configuring drawing properties (e.g., StrokeColor, FillColor, StrokeWidth).
  3. Defining shapes or paths using geometric types.
  4. Calling drawing methods on the ICanvas (e.g., DrawLine, DrawRectangle, DrawPath).

Core Concepts

ICanvas

The ICanvas interface is the primary entry point for all drawing operations. It represents the drawing surface and holds the current drawing state, including colors, transformations, and clipping regions.

Represents the drawing surface and provides methods for drawing various shapes and text.

Properties:

Methods:

See specific drawing primitive sections for methods like DrawLine, DrawRectangle, etc.

PathF

Represents a geometric path composed of one or more segments. Paths can be stroked (outlined) or filled.

PathF objects are built by adding various segments. They offer a flexible way to define complex shapes.

Methods:

PathF()
Creates a new empty path.
MoveTo(x, y)
Starts a new subpath at the specified coordinates.
LineTo(x, y)
Adds a line segment from the current point to the specified coordinates.
CubicTo(controlPoint1X, controlPoint1Y, controlPoint2X, controlPoint2Y, endPointX, endPointY)
Adds a cubic Bézier curve segment.
QuadTo(controlPointX, controlPointY, endPointX, endPointY)
Adds a quadratic Bézier curve segment.
Close()
Closes the current subpath by drawing a line from the current point to the starting point of the subpath.

Path Segments

MAUI Graphics uses a fluent API to construct paths. Common segments include:

IPaint

An interface representing a brush or drawing tool. The most common implementations are SolidPaint and gradient paints.

IPaint objects define how an area or line is colored. The canvas uses the current StrokePaint for outlines and FillPaint for filled areas.

Common Implementations:

Color

Represents an ARGB (Alpha, Red, Green, Blue) color value.

Colors can be created using static methods like Color.FromArgb("#RRGGBBAA") or Color.Parse("#RRGGBBAA").

var red = Color.Red;
var blue = Color.FromArgb(255, 0, 0, 255); // Opaque blue
var semiTransparentGray = Color.Parse("rgba(128, 128, 128, 0.5)");

Drawing Primitives

DrawLine(x1, y1, x2, y2)

Draws a straight line between two points.
void DrawLine(float x1, float y1, float x2, float y2)

This method draws a line using the current StrokeColor and StrokeWidth.

canvas.StrokeColor = Colors.Blue;
canvas.StrokeWidth = 2;
canvas.DrawLine(10, 10, 100, 100);

DrawRectangle(x, y, width, height)

Draws a rectangle. Can be stroked, filled, or both.
void DrawRectangle(float x, float y, float width, float height)

To fill the rectangle, set the FillColor. To stroke it, set the StrokeColor and StrokeWidth.

// Draw an outlined rectangle
canvas.StrokeColor = Colors.Green;
canvas.StrokeWidth = 3;
canvas.DrawRectangle(50, 50, 150, 100);

// Draw a filled rectangle
canvas.FillColor = Colors.Yellow;
canvas.FillRectangle(220, 50, 150, 100);

// Draw a filled and outlined rectangle
canvas.FillColor = Colors.Red;
canvas.StrokeColor = Colors.Black;
canvas.StrokeWidth = 1;
canvas.DrawRectangle(50, 200, 150, 100);

DrawEllipse(x, y, width, height)

Draws an ellipse within the specified bounding box.
void DrawEllipse(float x, float y, float width, float height)

Similar to DrawRectangle, you can control fill and stroke.

canvas.FillColor = Colors.Orange;
canvas.StrokeColor = Colors.Purple;
canvas.StrokeWidth = 2;
canvas.DrawEllipse(300, 200, 100, 50); // Ellipse wider than tall

DrawArc(x, y, radius, startAngle, endAngle, ...)

Draws an arc segment of an ellipse.
void DrawArc(float x, float y, float width, float height, float startAngle, float endAngle, bool closed = false, bool useCenter = false)

startAngle and endAngle are in degrees, with 0 degrees pointing to the right.

canvas.StrokeColor = Colors.Teal;
canvas.StrokeWidth = 4;
// Draw a pie slice (closed arc)
canvas.DrawArc(100, 350, 80, 80, 0, 90, closed: true, useCenter: true);
// Draw an open arc
canvas.DrawArc(220, 350, 80, 80, 180, 270, closed: false);

DrawText(text, x, y)

Draws text at a specified location.
void DrawText(string text, float x, float y)

Text drawing can be customized using the Font, TextColor, and TextAlign properties of the canvas.

canvas.Font = Font.SystemFontOfSize(18, FontSlant.Italic);
canvas.TextColor = Colors.DarkMagenta;
canvas.TextSize = 20;
canvas.TextAlign = HorizontalAlignment.Center;
canvas.DrawText("Hello MAUI Graphics!", 300, 450);

Transformations

Transformations allow you to manipulate the coordinate system of the canvas, affecting all subsequent drawing operations. The canvas maintains a transformation matrix. You can modify this matrix or save/restore its state.

Translate(dx, dy)

Moves the origin of the coordinate system by the specified distances.
void Translate(float dx, float dy)
canvas.StrokeColor = Colors.Brown;
canvas.StrokeWidth = 2;
canvas.Translate(50, 50); // Move origin 50px right, 50px down
canvas.DrawRectangle(0, 0, 100, 50); // This rectangle is now at (50, 50) relative to the original origin

Rotate(angle)

Rotates the coordinate system around the origin by the specified angle (in degrees).
void Rotate(float angle)
canvas.StrokeColor = Colors.Gray;
canvas.StrokeWidth = 2;
canvas.Translate(200, 150); // Move to a convenient center point
canvas.Rotate(45);         // Rotate by 45 degrees
canvas.DrawRectangle(-50, -25, 100, 50); // Rectangle is now rotated

Scale(scaleX, scaleY)

Scales the coordinate system by the specified factors.
void Scale(float scaleX, float scaleY)
canvas.StrokeColor = Colors.Olive;
canvas.StrokeWidth = 2;
canvas.Scale(2.0f, 0.5f); // Double width, half height
canvas.DrawEllipse(50, 50, 50, 50); // This ellipse will appear scaled

Concatenating Transformations

Transformations are applied in the order they are called. You can chain them to achieve complex effects.

canvas.StrokeColor = Colors.Indigo;
canvas.StrokeWidth = 3;
canvas.Translate(150, 100);
canvas.Rotate(30);
canvas.Scale(1.5f, 1.0f);
canvas.DrawLine(0, 0, 100, 0); // A line drawn after multiple transformations
Tip: Use canvas.SaveState() and canvas.RestoreState() to isolate transformations within specific drawing sections, ensuring they don't affect subsequent operations unintentionally.

Advanced Topics

Gradients

Create smooth color transitions for filling or stroking shapes.

MAUI Graphics supports linear and radial gradients. You define a sequence of colors and their positions along the gradient axis.

LinearGradientPaint

LinearGradientPaint(Color[] colors, PointF[] points)
var gradientStops = new Color[] { Colors.Red, Colors.Blue };
var gradientPoints = new PointF[] { new PointF(0, 0), new PointF(1, 1) }; // From top-left to bottom-right
canvas.FillPaint = new LinearGradientPaint(gradientStops, gradientPoints);
canvas.FillRectangle(10, 10, 150, 80);

RadialGradientPaint

RadialGradientPaint(Color[] colors, PointF[] points)
var gradientStops = new Color[] { Colors.Yellow, Colors.Orange };
var gradientPoints = new PointF[] { new PointF(0.5f, 0.5f), new PointF(1, 1) }; // Center to edge
canvas.FillPaint = new RadialGradientPaint(gradientStops, gradientPoints);
canvas.FillEllipse(200, 10, 100, 100);

Image Drawing

Draw images onto the canvas.
void DrawImage(IImage image, float x, float y, float width, float height)

You'll need to obtain an IImage object first, often from resources or by loading from a stream.

// Assuming 'myImage' is an IImage instance
// var myImage = await ImageSource.FromResource("MyApp.Resources.Images.myicon.png").ToImage(null);
// if (myImage != null)
// {
//     canvas.DrawImage(myImage, 10, 150, 80, 80);
// }

Clip Regions

Restrict drawing operations to a specific area.
void ClipPath(PathF path)

After calling ClipPath, any drawing operations will only be visible within the boundaries of the provided path. This is useful for masking or creating complex shapes.

var clipPath = new PathF();
clipPath.MoveTo(50, 300);
clipPath.LineTo(150, 300);
clipPath.LineTo(100, 400);
clipPath.Close();

canvas.ClipPath(clipPath);

canvas.FillColor = Colors.Fuchsia;
canvas.FillRectangle(0, 0, 500, 500); // Only the part of this rectangle inside the triangle path will be drawn

canvas.RestoreState(); // Important: remove the clip region if you want to draw outside it later.