在WPF中将canvas转换为writeablebitmap的最快方法?

时间:2013-04-17 02:03:40

标签: c# wpf writeablebitmap

我目前有一个writeablebitmap图像和带有绘图的画布,我想将图像发送给对等。为了减少带宽,我想将canvas转换为writeablebitmap,因此我可以将两个图像blit到a新的writeablebitmap。问题是我无法找到转换画布的好方法。 因此,我想问一下是否有直接的方法将画布转换为writeablebitmap类。

1 个答案:

答案 0 :(得分:5)

这取自this blog post,但不是写入文件,而是写入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);

}