Pregunta

I currently have one writeablebitmap image and canvas with drawings and I want to send the images to the peer.In order to reduce the bandwidth, I would like to convert canvas to the writeablebitmap, thus I can blit both the images to a new writeablebitmap. The problem is I cannot find a good way to convert the canvas. Therefore, I would like to ask if there is a direct way to convert the canvas to a writeablebitmap class.

¿Fue útil?

Solución

This is taken from this blog post but instead of writing to a file, it writes to a WriteableBitmap.

public WriteableBitmap SaveAsWriteableBitmap(Canvas surface)
{
    if (surface == null) return null;

    // Save current canvas transform
    Transform transform = surface.LayoutTransform;
    // reset current transform (in case it is scaled or rotated)
    surface.LayoutTransform = null;

    // Get the size of canvas
    Size size = new Size(surface.ActualWidth, surface.ActualHeight);
    // Measure and arrange the surface
    // VERY IMPORTANT
    surface.Measure(size);
    surface.Arrange(new Rect(size));

    // Create a render bitmap and push the surface to it
    RenderTargetBitmap renderBitmap = new RenderTargetBitmap(
      (int)size.Width, 
      (int)size.Height, 
      96d, 
      96d, 
      PixelFormats.Pbgra32);
    renderBitmap.Render(surface);


    //Restore previously saved layout
    surface.LayoutTransform = transform;

    //create and return a new WriteableBitmap using the RenderTargetBitmap
    return new WriteableBitmap(renderBitmap);

}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top