.netmauiskiasharpskia

.NET MAUI SkiaSharp SKCanvasView crash when size > 0


this is my first .NET Maui-App and I hope this is the right place to ask.

Right now I have problems using a SKCanvasView from SkiaSharp (Version 3.0.0-preview.4.1) in .NET 8 on Windows 11. Despite having all Exceptions turned on in the Exception Settings my debugger will crash with an unhandled exception as soon as width and height of the SkCanvasView are both changed to values > 0. I tried so many different combinations of Layouts/Width-/HeightRequests/Code-behind vs. XAML definition that by now I am totally clueless. I'd love to understand the problem which causes the crash to prevent it now and in the future, but I would highly appreciate a workaround with a SKCanvasView as well.

In MauiProgram.cs SkiaSharp is registered: builder.UseMauiApp<App>().UseMauiCommunityToolkit().UseSkiaSharp()

This is the reduced XAML-code which should use the SKCanvasView:

<?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:skia="clr-namespace:SkiaSharp.Views.Maui.Controls;assembly=SkiaSharp.Views.Maui.Controls"
             x:Class="FitnessApp.Views.SubPage1">
    <AbsoluteLayout x:Name="LayoutHelperView" BackgroundColor="LightBlue">
        <skia:SKCanvasView x:Name="skiaView" BackgroundColor="White"/>
        <Button x:Name="TestBtn" Text="Test SkiaView" Clicked="OnTestBtnClicked" />
    </AbsoluteLayout>
</ContentPage>

And that's the code-behind:

using FitnessApp.ViewModels;

namespace FitnessApp.Views;

public partial class SubPage1 : ContentPage
{
    public SubPage1(SubPage1ViewModel vm) {
        InitializeComponent();
        BindingContext = vm; 
    }

    private void OnTestBtnClicked(object sender, EventArgs e) {
        if (skiaView.Width == 0)
            skiaView.WidthRequest = 100;
        else
            skiaView.HeightRequest = 100;
    }
}

Additionally, in my minimum example there is a View-Model to the (sub) page, I use App-Shell to navigate to the sub page and Dependency Injection via services to instantiate the Model-Views and the page. Could there also be the error? But everything works as intended when I delete the SkCanvasView. Oh, and after updating I get new warnings like "Class 'SubPage1ViewModel' implements WinRT interfaces but isn't marked partial. Type should be marked partial for trimming and AOT compatibility if passed across the WinRT ABI." I am grateful for each hint.


Solution

  • Happens to me as well but only with latest visual studio 2022 17.11.5. It was working fine with vs2022 17.11.2 i didnt test versions in between. It seems to be related to this issue https://github.com/mono/SkiaSharp/issues/2999

    Workaround would be adding to csproj file this line:

    <WindowsSdkPackageVersion>10.0.19041.34</WindowsSdkPackageVersion>
    

    which works for me.