Skip to content
maui-graphics-drawing logo

.NET MAUI Graphics Drawing

maui-graphics-drawing

Guidance for custom drawing with Microsoft.Maui.Graphics, GraphicsView, canvas drawing operations, shapes, paths, text rendering, image drawing, shadows, clipping, and canvas state management. USE FOR: "custom drawing", "GraphicsView", "canvas drawing", "draw shapes", "draw path", "draw text", "I...

davidortinau/maui-skills0installs173stars

SKILL.md

Full skill instructions

.NET MAUI Graphics Drawing

Common gotchas

IssueFix
Nothing draws on screenEnsure Drawable is set on GraphicsView and the control has non-zero HeightRequest/WidthRequest
State bleeds between shapesWrap isolated sections in SaveState() / RestoreState() pairs
Shadows stick to later drawsCall canvas.SetShadow(SizeF.Zero, 0, null) after drawing the shadowed element
Clipping never resetsClipping is cumulative per frame — use SaveState/RestoreState around clip regions
UI freezes during drawingNever do I/​O, network, or heavy computation inside Draw() — it runs on the UI thread

Canvas state — always pair Save/​Restore

⚠️ Unpaired SaveState/RestoreState causes state leaks across draw calls.

// ✅ Correct — isolated state
canvas.SaveState();
canvas.StrokeColor = Colors.Red;
canvas.StrokeSize = 6;
canvas.DrawRectangle(10, 10, 80, 80);
canvas.RestoreState();
// Stroke reverts to previous values

// ❌ Wrong — state leaks to everything drawn after
canvas.StrokeColor = Colors.Red;
canvas.StrokeSize = 6;
canvas.DrawRectangle(10, 10, 80, 80);
// Every subsequent shape is now red with size 6

Saves/​restores: stroke, fill, font, shadow, clip, and transforms. Nest calls for layered isolation.

Triggering redraws

// ✅ Correct — queue a redraw
graphicsView.Invalidate();

// ❌ Wrong — never call Draw() directly
myDrawable.Draw(canvas, rect);
  • Invalidate() queues a redraw; the framework calls IDrawable.Draw on the next frame.
  • ⚠️ Avoid calling Invalidate() in a tight loop — batch state changes, then invalidate once.

Performance tips

  • Keep Draw() fast — pre-compute paths and data outside the draw method; Draw() is called on every frame.
  • Reuse PathF objects — create them once, store as fields, draw repeatedly.
  • Use MeasureFirstItem-style thinking — if drawing many identical items, calculate dimensions once.
  • Minimize allocations — avoid new PathF() inside Draw() when the path doesn't change.
// ✅ Pre-computed path (field)
private readonly PathF _starPath = BuildStarPath();

public void Draw(ICanvas canvas, RectF dirtyRect)
{
    canvas.FillPath(_starPath);
}

// ❌ Allocating every frame
public void Draw(ICanvas canvas, RectF dirtyRect)
{
    var path = new PathF();
    // ...build path every frame...
    canvas.FillPath(path);
}

Shadows and clipping — sticky state pitfalls

Shadows apply to all subsequent draws until explicitly removed. Clips accumulate and can only be undone with RestoreState():

// ✅ Shadow: remove after use
canvas.SetShadow(new SizeF(5, 5), 4, Colors.Gray);
canvas.FillRectangle(20, 20, 100, 60);
canvas.SetShadow(SizeF.Zero, 0, null); // ← must remove

// ✅ Clip: isolate with SaveState/​RestoreState
canvas.SaveState();
canvas.ClipRectangle(20, 20, 100, 100);
canvas.FillRectangle(0, 0, 200, 200); // clipped
canvas.RestoreState();                  // clip removed

// ❌ Clip persists — everything after is also clipped
canvas.ClipRectangle(20, 20, 100, 100);
canvas.FillEllipse(150, 150, 50, 50); // unintentionally clipped!

Set properties BEFORE draw calls

// ✅ Properties then draw
canvas.StrokeColor = Colors.Blue;
canvas.DrawRectangle(10, 10, 100, 50);

// ❌ Setting after draw has no effect on previous shape
canvas.DrawRectangle(10, 10, 100, 50);
canvas.StrokeColor = Colors.Blue;

Decision framework

NeedApproach
Simple shapes / static graphicsSingle IDrawable, draw in Draw()
Animated graphicsUpdate state externally, call Invalidate() from timer/​animation
Complex layered sceneMultiple SaveState/RestoreState blocks, or separate drawables
Hit testing on drawn elementsTrack shape bounds manually — GraphicsView has no built-in hit test on drawn content
Platform-specific renderingUse handlers/​platform code; Microsoft.Maui.Graphics is cross-platform only

Quick checklist

  • GraphicsView has Drawable set and non-zero size
  • Draw() is fast — no I/​O, no heavy allocations
  • Every SaveState() has a matching RestoreState()
  • Shadows removed with SetShadow(SizeF.Zero, 0, null) after use
  • Clips wrapped in SaveState/RestoreState blocks
  • Properties set before the draw call they apply to
  • Invalidate() used instead of calling Draw() directly

More skills from davidortinau

maui-aspire logo
davidortinau/maui-skills

maui-aspire

Guide for .NET MAUI apps consuming .NET Aspire-hosted backend services. Covers AppHost configuration, service discovery for mobile clients, HttpClient DI setup, Entra ID authentication with MSAL.NET for calling protected APIs, development workflow (Aspire dashboard + MAUI debugging), Blazor Hybri...

173 0
View
maui-maps logo
davidortinau/maui-skills

maui-maps

Guidance for adding map controls, pins, polygons, polylines, geocoding, Google Maps API key configuration, and platform setup in .NET MAUI apps using Microsoft.Maui.Controls.Maps. USE FOR: "add map", "map control", "map pins", "polygons on map", "polylines", "geocoding", "Google Maps API key", "M...

173 0
View
maui-hybridwebview logo
davidortinau/maui-skills

maui-hybridwebview

Guidance for embedding web content in .NET MAUI apps using HybridWebView, including JavaScript–C# interop, bidirectional communication, raw messaging, and trimming/NativeAOT considerations. USE FOR: "HybridWebView", "JavaScript interop", "embed web content", "JS to C# interop", "C# to JavaScript"...

173 0
View
maui-safe-area logo
davidortinau/maui-skills

maui-safe-area

.NET MAUI safe area and edge-to-edge layout guidance for .NET 10+. Covers SafeAreaEdges property, SafeAreaRegions enum, per-edge control, keyboard avoidance, Blazor Hybrid CSS safe areas, migration from legacy APIs, and platform-specific behavior for Android, iOS, and Mac Catalyst. USE FOR: "safe...

173 0
View
maui-app-lifecycle logo
davidortinau/maui-skills

maui-app-lifecycle

.NET MAUI app lifecycle guidance covering the four app states (not running, running, deactivated, stopped), cross-platform Window lifecycle events, backgrounding and resume behaviour, platform-specific lifecycle mapping for Android and iOS/Mac Catalyst, and state-preservation patterns. USE FOR: "...

173 0
View
maui-collectionview logo
davidortinau/maui-skills

maui-collectionview

Guidance for implementing CollectionView in .NET MAUI apps — data display, layouts (list & grid), selection, grouping, scrolling, empty views, templates, incremental loading, swipe actions, and pull-to-refresh. USE FOR: "CollectionView", "list view", "grid layout", "data template", "item template...

173 0
View
maui-sqlite-database logo
davidortinau/maui-skills

maui-sqlite-database

Add SQLite local database storage to .NET MAUI apps using sqlite-net-pcl. Covers data models with ORM attributes, async database service with lazy init, DI registration, WAL mode, and file management. Works with any UI pattern (XAML/MVVM, C# Markup, MauiReactor). USE FOR: "SQLite database", "loca...

173 0
View
maui-dependency-injection logo
davidortinau/maui-skills

maui-dependency-injection

Guidance for dependency injection in .NET MAUI apps — service registration, lifetime selection (Singleton/Transient/Scoped), constructor injection, automatic resolution via Shell navigation, explicit resolution patterns, platform-specific registrations, and testability best practices. USE FOR: "d...

173 0
View
maui-custom-handlers logo
davidortinau/maui-skills

maui-custom-handlers

Guide for creating custom .NET MAUI handlers, customizing existing handlers with property mappers, and implementing platform-specific native views. Covers PrependToMapping/ModifyMapping/AppendToMapping, PropertyMapper, CommandMapper, partial handler classes, and handler registration. USE FOR: "cu...

173 0
View
maui-performance logo
davidortinau/maui-skills

maui-performance

Performance optimization guidance for .NET MAUI apps covering profiling, compiled bindings, layout efficiency, image optimization, resource dictionaries, startup time, trimming, and NativeAOT configuration. USE FOR: "performance optimization", "slow startup", "app performance", "compiled bindings...

173 0
View
maui-theming logo
davidortinau/maui-skills

maui-theming

Guide for theming .NET MAUI apps—light/dark mode support, AppThemeBinding, dynamic resources, ResourceDictionary theme switching, and system theme detection. USE FOR: "dark mode", "light mode", "theming", "AppThemeBinding", "theme switching", "ResourceDictionary theme", "dynamic resources", "syst...

173 0
View
maui-accessibility logo
davidortinau/maui-skills

maui-accessibility

Guide for making .NET MAUI apps accessible — screen reader support via SemanticProperties, heading levels, AutomationProperties visibility control, programmatic focus and announcements, and platform-specific gotchas for TalkBack, VoiceOver, and Narrator. USE FOR: "add accessibility", "screen read...

173 0
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View