Search code examples
c#uwpwin2d

In Win2d canvasControl , how to call createResources event multiple times whenever needed?


I have a canvasControl,in that CreateResources Event is fired only once when I run the Program.I had a FilePicker to pick an image source from local.Whenever an Image is Picked , i need to Call CreateResources event to load the Resources and then draw it using canvasBitmap and DrawingSession. I Know how to Draw but,I Don't Know how to Load Resources Whenever an image is picked.Can anyone Suggest me ,how to achieve this??


Solution

  • in Win2D, the CreateResource event is only triggered when the CanvasControl is loading, that is, it will only be triggered once.

    If you need to create resources after this, you need to create a custom LoadResourcesForLevelAsync method:

    async Task LoadResourcesForLevelAsync(CanvasControl resourceCreator, int level)
    {
        levelBackground = await CanvasBitmap.LoadAsync(resourceCreator, ...);
        levelThingie = await CanvasBitmap.LoadAsync(resourceCreator, ...);
        // etc.
    }
    

    This is explained in the Win2D documentation, please refer to this document:


    Update

    A simple example of loading pictures in the Draw event:

    private string imageFilePath = @"ms-appx:///Assets/StoreLogo.png";
    private CanvasBitmap img;
    
    private void CanvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
    {
        if (img != null)
        {
            args.DrawingSession.DrawImage(img);
        }
        else
        {
            GetImage().Wait();
        }
        async Task GetImage()
        {
            await Task.Run(async () =>
            {
                img = await CanvasBitmap.LoadAsync(sender, new Uri(imageFilePath));
            }).ConfigureAwait(false);
        }
    }
    

    Thanks.