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:
- Obtaining an
ICanvasinstance. - Configuring drawing properties (e.g.,
StrokeColor,FillColor,StrokeWidth). - Defining shapes or paths using geometric types.
- 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.
Properties:
StrokeColor: The color used for drawing lines and outlines.FillColor: The color used for filling shapes.StrokeWidth: The width of lines and outlines.Transform: The current transformation matrix applied to the canvas.Alpha: The global alpha value (transparency) for all drawing operations.
Methods:
See specific drawing primitive sections for methods like DrawLine, DrawRectangle, etc.
PathF
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:
- Move To: Establishes a new starting point for a path.
- Line To: Draws a straight line to a specified point.
- Cubic Bézier: Draws a smooth curve defined by two control points and an endpoint.
- Quadratic Bézier: Draws a curve defined by one control point and an endpoint.
- Close Path: Connects the current point back to the start of the subpath.
IPaint
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:
SolidPaint: Fills or strokes with a single color.LinearGradientPaint: Fills or strokes with a linear color gradient.RadialGradientPaint: Fills or strokes with a radial color gradient.
Color
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)
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)
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)
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, ...)
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)
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)
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)
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)
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
canvas.SaveState() and canvas.RestoreState() to isolate transformations within specific drawing sections, ensuring they don't affect subsequent operations unintentionally.
Advanced Topics
Gradients
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
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
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.