How to Draw 2D Graphics in .NET MAUI’s GraphicsView

jollenmoyani

Jollen Moyani

Posted on November 18, 2022

How to Draw 2D Graphics in .NET MAUI’s GraphicsView

If you need to draw 2D graphical objects in your application without a platform handler in .NET MAUI, then you can use the cross-platform graphics canvas, GraphicsView, that .NET MAUI provides. This GraphicsView can be accessed using the Microsoft.Maui.Graphics namespace. This canvas supports drawing and painting shapes and images, compositing operations, and transforming graphical object.

GraphicsView defines a Drawable property, of type IDrawable , that is responsible for drawing your 2D objects within the Draw() method. The Draw() method will be called each time the GraphicsView is invalidated.

Class Diagram of GraphicsView

GraphicsView Class Diagram

In this blog, let’s see how to draw 2D graphics using the GraphicsView canvas in your .NET MAUI application.

Creating a GraphicsView

The GraphicsView control should define the IDrawable interface that specifies the drawable content. So, first create a class named GraphicsDrawable that is inherited from the IDrawable interface and then implement its Draw method.

Refer to the following code example.

namespace _2DGraphicsDrawing;

public class GraphicsDrawable : IDrawable
{
   public void Draw(ICanvas canvas, RectF dirtyRect)
   {
      // Drawing code goes here
   }
}
Enter fullscreen mode Exit fullscreen mode

The Draw method has the following two arguments:

  • ICanvas: The drawing canvas that contains the abstraction of native canvas APIs to draw graphical objects.
  • RectF: A structure that defines the size and location data of the drawing canvas.

The following code example shows how to add the GraphicsView control to a .NET MAUI app and assign the IDrawable object.

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:_2DGraphicsDrawing"
             x:Class="_2DGraphicsDrawing.MainPage">
 <ContentPage.Resources>
  <local:GraphicsDrawable x:Key="drawable"/>
 </ContentPage.Resources>
 <VerticalStackLayout>
  <GraphicsView Drawable="{StaticResource drawable}"
                HeightRequest="500"
                WidthRequest="500" />
  </VerticalStackLayout>

</ContentPage>
Enter fullscreen mode Exit fullscreen mode

With the setup to draw in a .NET MAUI application completed, lets focus on drawing simple shapes and string values.

Drawing a line

You can draw a line on the ICanvas interface using the DrawLine method. This method requires four arguments of type float that specify the x and y coordinates of start and stop points of the line.

The following code example shows how to draw a simple line using the DrawLine method.

public class GraphicsDrawable : IDrawable
{
  public void Draw(ICanvas canvas, RectF dirtyRect)
  {
    canvas.StrokeColor = Colors.Red;
    canvas.StrokeSize = 6;
    canvas.DrawLine(10, 10, 100, 100);
   }
}
Enter fullscreen mode Exit fullscreen mode

Drawing a Simple Line Using the GraphicsView Canvas in .NET MAUI

Drawing a Simple Line Using the GraphicsView Canvas in .NET MAUI

Drawing an ellipse

To draw an ellipse or a circle on the ICanvas, use the DrawEllipse method. The DrawEllipse method takes four arguments, x, y, width, and height, of type float, that represent the starting point and size (width and height) of the ellipse.

Note: To draw a circle, specify the same values to the width and height arguments in the DrawEllipse method.

Refer to the following code example.

public void Draw(ICanvas canvas, RectF dirtyRect)
{
   canvas.StrokeColor = Colors.Red;
   canvas.StrokeSize = 4;
   canvas.DrawEllipse(10, 10, 100, 50);
}
Enter fullscreen mode Exit fullscreen mode

Drawing an Ellipse Using the GraphicsView Canvas in .NET MAUI

Drawing an Ellipse Using the GraphicsView Canvas in .NET MAUI

To draw a filled ellipse, use the FillEllipse method with the same set of arguments.

Drawing a rectangle

We can easily draw rectangles and squares on the ICanvas using the DrawRectangle method. This method takes x, y, width, and height arguments, of type float, that represent the start position and size of the rectangle or square.

Note: To draw a square, specify the same values in the width and height arguments in the DrawRectangle method.

Refer to the following code example to draw a rectangle.

public void Draw(ICanvas canvas, RectF dirtyRect)
{
  canvas.StrokeColor = Colors.Red;
  canvas.StrokeSize = 4;
  canvas.DrawRectangle(10, 10, 100, 50);
}
Enter fullscreen mode Exit fullscreen mode

Drawing a Rectangle Using the GraphicsView Canvas in .NET MAUI

Drawing a Rectangle Using the GraphicsView Canvas in .NET MAUI

A filled rectangle can be drawn using the FillRectangle method on the ICanvas with the same set of arguments.

Drawing an arc

Let’s draw an arc on the ICanvas using the DrawArc method. To do so, we require the x, y, width, height, startAngle, and endAngle arguments, of type float; and clockwise and closed arguments, of type bool.

Refer to the following code example.

public void Draw(ICanvas canvas, RectF dirtyRect)
{
  canvas.StrokeColor = Colors.Red;
  canvas.StrokeSize = 4;
  canvas.DrawArc(10, 10, 100, 100, 0, 180, true, false);
}
Enter fullscreen mode Exit fullscreen mode

Drawing an Arc Using the GraphicsView Canvas in .NET MAUI

Drawing an Arc Using the GraphicsView Canvas in .NET MAUI

A filled arc can be drawn using the FillArc method on ICanvas with the same set of arguments.

Drawing a path

A path is a collection of one or more contours that consists of straight lines, quadratic curves, and cubic curves.

We can use the paths to draw curves and complex shapes on the ICanvas using the DrawPath method, which requires a PathF argument.

A contour generally begins with a call to the PathF.MoveTo method, which establishes a point at the beginning of the contour and an initial current point. You can then call the following methods to continue the contour with a line or curve shape:

  • LineTo: Adds a straight line to the path.
  • AddArc: Adds an arc.
  • CurveTo: Adds a cubic Bezier spline.
  • QuadTo: Adds a quadratic Bezier spline.

The following code example shows how to draw a path.

Public void Draw (Icanvas canvas, RectF dirtyRect)
{
  PathF path = new PathF();
  path.MoveTo(40, 10);
  path.LineTo(70, 80);
  path.LineTo(10, 50);
  path.Close();
  canvas.StrokeColor = Colors.Red;
  canvas.StrokeSize = 6;
  canvas.DrawPath(path);
}
Enter fullscreen mode Exit fullscreen mode

Drawing a Path Using the GraphicsView Canvas in .NET MAUI

Drawing a Path Using the GraphicsView Canvas in .NET MAUI

A filled path can be drawn using the FillPath method in ICanvas.

Drawing a string

Now, let’s see how to draw strings on ICanvas using the DrawString method. We can define the appearance of each string by setting the Font , FontColor , and FontSize properties of ICanvas. To align the strings, specify the horizontal and vertical alignment options in the DrawString method to perform alignment within the bounding box.

The following code example shows how to draw strings.

Public void Draw(Icanvas canvas, RectF dirtyRect)
{
   canvas.FontColor = Colors.Red;
   canvas.FontSize = 18;
   canvas.DrawString(Text is left aligned., 20, 20, 380, 100, HorizontalAlignment.Left, VerticalAlignment.Top);
   canvas.DrawString(Text is centered., 20, 60, 380, 100, HorizontalAlignment.Center, VerticalAlignment.Top);
   canvas.DrawString(Text is right aligned., 20, 100, 380, 100, HorizontalAlignment.Right, VerticalAlignment.Top);
}
Enter fullscreen mode Exit fullscreen mode

Drawing String Elements Using the GraphicsView Canvas in .NET MAUI

Drawing Strings Using the GraphicsView Canvas in .NET MAUI

Drawing free hand signatures using the GraphicsView in .NET MAUI

In the previous examples, we learned how to use the GraphicsView control to create simple shapes and text.

Now, let’s see how to create a signature in your .NET MAUI app.

Note: To get the realistic look and feel of a handwritten signature, use the Syncfusion .NET MAUI SignaturePad control.

Follow these steps to capture and freehand draw using the GraphicsView control:

Step 1 : Create the SignatureView class, extended from the GraphicsView control.

public class SignatureView : GraphicsView
{
}
Enter fullscreen mode Exit fullscreen mode

Step 2 : Then, create an object of type GraphicsDrawable and assign it to the Drawable property of the SignatureView.

public SignatureView()
{
  graphicsDrawable = new GraphicsDrawable();
  this.Drawable = graphicsDrawable;
}
Enter fullscreen mode Exit fullscreen mode

Step 3 : The GraphicsView provides the events support to detect interaction with the touch pointers such as start, drag, and end interactions. Using this support, we can get the touch interaction points on each move. Now, call the Invalidate() method within the event to draw the signature based on every touch movement in the drawable part.

Public SignatureView()
{
  this.StartInteraction += SignatureView_StartInteraction;
  this.DragInteraction += SignatureView_DragInteraction;
  this.EndInteraction += SignatureView_EndInteraction;

}
private void SignatureView_DragInteraction(object sender, TouchEventArgs e)
{
   graphicsDrawable.DragPoints.Add(e.Touches[0]);
   this.Invalidate();
}

private void SignatureView_StartInteraction(object sender, TouchEventArgs e)
{
    graphicsDrawable.StartPoint = e.Touches[0];
    this.Invalidate();
}
Enter fullscreen mode Exit fullscreen mode

Step 4 : Draw signatures using the Draw method, which has ICanvas and view bounds. Using this method, you can also draw a background for view bounds and signatures based on the captured interaction points.

public void Draw(ICanvas canvas, RectF dirtyRect)
{
   canvas.FillColor = Colors.CornflowerBlue;
   canvas.FillRectangle(dirtyRect);

   PathF path = new PathF();
   if (DragPoints?.Count > 0)
   {
      path.MoveTo(StartPoint.X, StartPoint.Y);
      foreach (var point in DragPoints)
      {
         path.LineTo(point);
      }
      canvas.StrokeColor = Colors.Red;
      canvas.StrokeSize = 2;

      canvas.DrawPath(path);
   }
}
Enter fullscreen mode Exit fullscreen mode

That’s it! You can now create your signatures with the help of the .NET MAUI 2D graphics canvas. Refer to the following GIF image.

Drawing a Signature Using the GraphicsView Canvas in .NET MAUI

Drawing a Signature Using the GraphicsView Canvas in .NET MAUI

GitHub reference

For more details, refer to the complete code example for drawing signatures using the GraphicsView in .NET MAUI.

Conclusion

Thanks for reading! In this blog post, we have seen how to draw 2D graphics in your .NET MAUI applications using the GraphicsView canvas. Try out the procedures in this blog and leave your feedback in the comments section below!

Syncfusion .NET MAUI controls were built from scratch using .NET MAUI, so they feel like framework controls. They are fine-tuned to work with a huge volume of data. Use them to build better cross-platform mobile and desktop apps!

For current customers, the new Essential Studio version is available for download from the License and Downloads page. If you are not yet a Syncfusion customer, you can always download our free evaluation to see all our controls in action.

For questions, you can contact us through our support forum, support portal, or feedback portal. We are always happy to assist you!

Related blogs

💖 💪 🙅 🚩
jollenmoyani
Jollen Moyani

Posted on November 18, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related