Question

I'm trying to make an Image out of one of my Canvas (myPrintingCanvas). But the Width of the image is getting atleast twice wider than the Canvas, and the extra space that is created is back. If I try on another Canavas (LayoutRoot), it works as intended.

My observation is that on myPrintingCanvas the ActualWidth is always 0. LayoutRoot has a correct ActualWidth. Not sure if it has anything to do with the extra padding, and I have failed on getting the ActualWidth for myPrintingCanvas (using UpdateLayout and Measure).

Code:

//Code to render the content of myPrintingCanvas
...

//Make the WriteableBitmap 
WriteableBitmap myWriteableBitmap = new WriteableBitmap(myPrintingCanvas, null);
Was it helpful?

Solution

Have you tried Creating the WriteableBitmap with a fixed size and then calling its Render method to render the bitmap? Canvas has some weird behaviors because it is an anti-pattern in Silverlight and WPF and breaks many rules about layout. The code for creating a fixed size WriteableBitmap and rendering to it would look something like this:

        int width = 640;
        int height = 480;
        WriteableBitmap bmp = new WriteableBitmap(width, height);
        bmp.Render(myPrintingCanvas, null);
        bmp.Invalidate();

One advantage of this technique is that if you need to grab multiple images you can reuse the same WriteableBitmap instead of recreating it every time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top