c# - 在 WPF 中将 Canvas 转换为可写位图的最快方法?

标签 c# wpf writeablebitmap

我目前有一个可写的位图图像和一个带有绘图的 Canvas ,我想将图像发送给对等方。为了减少带宽,我想将 Canvas 转换为可写的位图,这样我就可以将两个图像 blit 到一个新的可写位图。问题是我找不到转换 Canvas 的好方法。 因此,我想请问是否有直接的方法将 Canvas 转换为可写位图类。

最佳答案

这取自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);

}

关于c# - 在 WPF 中将 Canvas 转换为可写位图的最快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16050202/

相关文章:

c# 继承和向下继承层次结构

c# - 如何将 PDF 文件转换为图像

c# - 如何使用wpf xaml绘制均匀间隔的对角线文本

silverlight - PixelFormats 和 WriteableBitmap.Lock 在 Silverlight3 中去了哪里?

c# - DateTime.Now 缺少 1 小时夏令时

c# - 将 C# 片段转换为 Java

c# - 知道usercontrol的处置事件?

javascript - 如何将信息从 WPF 应用程序传递到 HTML 页面

windows-phone-8 - WriteableBitmapRenderer.RenderAsync() ArgumentException "Value does not fall within the expected range"

c# - 如何将可写位图的一部分复制到另一个可写位图?