我目前有一个可写的位图图像和一个带有绘图的 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/