2013-04-17 79 views
3

我目前有一个writeablebitmap图像和画布与图纸,我想发送图像到peer.为了减少带宽,我想转换成writeablebitmap的画布,因此我可以blit两个图像到一个新的WriteableBitmap的。问题是我找不到转换画布的好方法。 因此,我想问问是否有直接的方法将画布转换为writeablebitmap类。将画布转换为WPF中writeablebitmap的最快方法?

+0

我正在使用C#与WPF。 –

回答

4

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

} 
相关问题