3

I am trying to render some lines on a .NET MAUI GraphicsView. The lines are stored as Vector2 data in an array on my MainPage.

My problem is that I don't know how to pass variable data from the MainPage into the Draw() method of the IDrawable class. In the GraphicsViewDemos are a lot of examples but they load files from the app's ressources and they don't show how to pass data into it. My goal is to update the canvas in realtime.

Here is an example of a single hardcoded line from the demos:

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

In the Mainpage.xaml is following code:

<ContentPage.Resources>
    <drawable:GraphicsDrawable x:Key="drawable" />
</ContentPage.Resources>

and

<GraphicsView Drawable="{StaticResource drawable}"
              HeightRequest="300"
              WidthRequest="400" />

1 Answer 1

3

You could pass the array of Vector2 values via Binding:

Drawable

Create a BindableProperty as follows:

internal class GraphicsDrawable: IDrawable
{
    public Vector2[] Vectors
    {
       get => (Vector2[])GetValue(VectorsProperty);
       set => SetValue(VectorsProperty, value);
    }

    public static BindableProperty VectorsProperty = BindableProperty.Create(nameof(Vectors), typeof(Vector2[]), typeof(GraphicsDrawable));

    public void Draw(ICanvas canvas, RectF dirtyRect)
    {
        canvas.StrokeColor = Colors.Red;
        canvas.StrokeSize = 6;

        //Use vectors here
        canvas.DrawLine(Vectors[0].X, Vectors[0].Y, Vectors[1].X, Vectors[1].Y);
    }
}

ViewModel

Assuming you have your array defined as follows:

private Vector2[] _vectorArray;
public Vector2[] VectorArray
{
    get => _vectorArray;
    set
    {
        if(_vectorArray == value) return;
        _vectorArray = value;
        OnPropertyChanged();
    }
}

View

In your view, you can now bind to the property:

<GraphicsView HeightRequest="300"
              WidthRequest="400">
    <GraphicsView.Drawable>
       <GraphicsDrawable Vectors="{Binding VectorArray}" />
    </GraphicsView.Drawable>
</GraphicsView>

Note: You cannot use your GraphicsDrawable as a StaticResource, because then the value changes won't be propagated. Also, using it as a resource generally shouldn't be necessary in your scenario.

This is just one way, an MVVM-way, to do it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.