Creating a drawable control in MAUI

MAUI includes relatively primitive graphics drawing options for the developer. Your class can implement the IDrawable interface and be assigned to a GraphicsView visual element.

So for example, let’s implement a barebones IDrawable

internal class MyDrawable : IDrawable
{
    public void Draw(ICanvas canvas, RectF dirtyRect)
    {
        canvas.DrawRectangle(1, 1, dirtyRect.Width, dirtyRect.Height);
    }
}

Obviously this does very little of interest except draws a rectangle in the view area that the code which hosts the drawable take up.

So to display this in our XAML we declare the drawable as a resource, like this

<ContentPage.Resources>
   <drawables:MyDrawable x:Key="MyDrawable" />
</ContentPage.Resources>

Finally we assign this drawable to a Graphics views which hosts the drawable like this

<GraphicsView Drawable="{StaticResource MyDrawable}"
   HeightRequest="120"
   WidthRequest="400" />

The ICanvas used within the IDrawable offers a lot of methods to draw lines, rectangles, text etc.

Note: It reminds me of the Canvas in Delphi all those many years back.

Ofcourse, we might prefer to remove the requirement of using resources and the GraphicsView. We’re not really removing them so much as just creating our own GraphicsView, so for example let’s create our control like this

public class MyGraphics : GraphicsView
{
    public MyGraphics()
    {
        Drawable = new MyDrawable();
    }
}

and now we can just use like this

<MyGraphics 
   HeightRequest="120"
   WidthRequest="400" />