Canvas to WriteableBitmap

Gonzalez, Javier 0 Reputation points
2025-01-31T21:18:14.6766667+00:00

Hello.

I'm imported an images and loaded in a WriteableBitmap.

Then i loaded that image in a Image variable. I need to draw a simple square . For that my next step was to load the Image variable in a canvas. Using a polygon i was able to draw a simple square and show in the app as canvas, but i need save as WriteableBitmap. I tried to use:

RenderTargetBitmap renderBitmap = new RenderTargetBitmap();

          await renderBitmap.RenderAsync(canvas);

But the resutl is 0 bytes in renderBitmap.

Universal Windows Platform (UWP)
Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
5,399 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Roy Li - MSFT 33,671 Reputation points Microsoft Vendor
    2025-02-04T02:34:23.2533333+00:00

    Hello,

    Welcome to Microsoft Q&A!

    I checked your code, I found that you haven't rendered your canvas2 into UI, right?

    RenderTargetBitmap could only capture content that in the XAML visual tree. That means that you need to render your Canvas first in your UI. For example, add the canvas2 to your page's root element to make it visible. Then you could add the image and call the RenderAsync method to capture the content.

    Thank you.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. Gonzalez, Javier 0 Reputation points
    2025-02-04T13:02:14.57+00:00

    Thanks Roy:

    Let me check if my understanding is correct:

    In the UI I created a Grid <Grid x:Name="RenderedGrid"> inside the Grid I made visible canvas2.

    After that I done:

    RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();

            await renderTargetBitmap.RenderAsync(RenderedGrid, 1432, 625);
    
            MyImageout.Source = renderTargetBitmap; //For show  in  <Image x:"MyImageout" >
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.