Home > Mobile >  MAUI Draw line on canvas during runtime after button click
MAUI Draw line on canvas during runtime after button click

Time:09-26

I want to draw a new line in a GraphicsView after the click of a button. This will draw the line on startup but I would like to either redraw the current line or preferably add another line to the view.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:controls="clr-namespace:CoachesToolbox.Controls"
             xmlns:viewmodel="clr-namespace:CoachesToolbox.ViewModel"
             xmlns:mct="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
             xmlns:drawable="clr-namespace:CoachesToolbox.Models"
             x:DataType="viewmodel:MainViewModel"
             x:Class="CoachesToolbox.Views.MainPage"
             Title="CoachesToolBox demos"
             >
    <ContentPage.Resources>
        <drawable:Drawable x:Key="MyDrawable" />

    </ContentPage.Resources>
<GraphicsView x:Name="Canvas"
                          HorizontalOptions="Fill"
                          VerticalOptions="Fill"
                          Drawable="{StaticResource MyDrawable}"
                          Grid.Column="1"
                          Grid.Row="0"
                          BackgroundColor="Transparent"/>
namespace CoachesToolbox.Models
{
    public class Drawable : IDrawable
    {
        public void Draw(ICanvas canvas, RectF dirtyRect)
        {
            canvas.StrokeColor = Colors.Red;
            canvas.StrokeSize = 5;
            canvas.DrawLine(10, 10, 90, 100);
        }
    }
}

CodePudding user response:

Unfortunately, drawing on a canvas doesn't work that way. You can't "add" something on a canvas. It just draws what you tell it to draw.

You could increment an int with each button click and have a for loop to draw each line.

CodePudding user response:

remove attribute Drawable on Canvas. // to test.

add x:name="NAMED_RESOURCE" to resource declaration in ContentPage.Resource

add button with clicked event.

<Button 
    Text="Add Drawing"
    Clicked="Button_Clicked" 
    VerticalOptions="Start"
    HorizontalOptions="Center"></Button>

private void Button_Clicked(object sender, EventArgs e)
{
    Canvas.Drawable = NAME_RESOURCE;
}
  • Related