Search code examples
c#androidmauiskia

How to detect SKCanvasView full size


Environment: Visual Studio 2022, MAUI Android application, SkiaSharp.Views.Maui.Controls nuget 2.88.6.

I am trying to draw SKImage in the whole window, stretching it to full width and height. Actually, it is drawn with 1/2 width and height. How can I find the full rectangle from PaintSurface message handler?

MainPage.xaml.cs:

using Android.Graphics;
using SkiaSharp;
using SkiaSharp.Views.Maui.Controls;
...

public partial class MainPage : ContentPage
{
    SKImage image;
    SKCanvasView canvasView;

    public MainPage()
    {
        InitializeComponent();

        // ... Other initialization

        canvasView = new SKCanvasView();
        canvasView.PaintSurface += CanvasView_PaintSurface;
        Content = canvasView;
    }

    private void CanvasView_PaintSurface(object sender, SkiaSharp.Views.Maui.SKPaintSurfaceEventArgs e)
    {
        var cv = e.Surface.Canvas;          // SKCanvas

        cv.Clear(new SKColor(0, 0, 255));   // OK, the whole window is blue

        // Left-top point, 1:1
        //cv.DrawImage(image, new SKPoint(0, 0));

        // Trying to draw on the whole area - actually draws about 1/2 width and height
        cv.DrawImage(image, new SKRect(0.0f, 0.0f, (float)canvasView.Width, (float)canvasView.Height));
    }
}

MainPage.xaml contains only ContentPage:

<?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"
         x:Class="BitmapTest2.MainPage">
</ContentPage>

Solution

  • What you needed was instead of using Canvas's Height and Width, which are calculated when you add the view to the screen you should check the Info from your PaintSurface's EventsArgs, where the current available space of the Canvas is.

    So what you would do is something like below

    In your CanvasView_PaintSurface method

    var info = e.Info;
    var height = info.Height;
    var width = info.Width;