在WPF中把Canvas保存为图片,文本文件,xps文件

由于wpf的UI使用xaml来表达的,所以我们们可利用这个优点,把WPF中的xaml元素另存为各样的文件,在很多时候我们都不须要这样的操作。把xaml保存为图片、字符串、XPS等等。这里我写了一些方法,以供大家参考.。

注意:以下保存操作前,一定要确保参数中的canvas有高和宽。

1.把canvas保存为文本文件

using System.IO;
public void Export(Uri path, Canvas surface)
{
      if (path == null) return;
      if (surface == null) return;
      string xaml = XamlWriter.Save(surface);
      File.WriteAllText(path.LocalPath, xaml);
}

2.把canvas保存为xps文件,xps命名空间在ReachFramework.dll中

   using System.IO.Packaging;
   using System.Windows.Xps;
   using System.Windows.Xps.Packaging;
   using System.IO;
   public void Export(Uri path, Canvas surface)
   {
       if (path == null) return;
    
       Transform transform = surface.LayoutTransform;
       surface.LayoutTransform = null;
    
       Size size = new Size(surface.Width, surface.Height);
       surface.Measure(size);
      surface.Arrange(new Rect(size));
   
      Package package = Package.Open(path.LocalPath, FileMode.Create);
      XpsDocument doc = new XpsDocument(package);
      XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc);
      writer.Write(surface);
      doc.Close();
      package.Close();
      surface.LayoutTransform = transform;
  }

3.把canvas保存为图片

public void ExportToPng(Uri path, Canvas surface)
   {
       if (path == null) return;
    
       Transform transform = surface.LayoutTransform;
       surface.LayoutTransform = null;
    
       Size size = new Size(surface.Width, surface.Height);
       surface.Measure(size);
       surface.Arrange(new Rect(size));
   
       RenderTargetBitmap renderBitmap =
       new RenderTargetBitmap(
       (int)size.Width,
       (int)size.Height,
       96d,
       96d,
       PixelFormats.Pbgra32);
       renderBitmap.Render(surface);
  
       using (FileStream outStream = new FileStream(path.LocalPath, FileMode.Create))
       {
           PngBitmapEncoder encoder = new PngBitmapEncoder();
           encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
           encoder.Save(outStream);
       }
           surface.LayoutTransform = transform;
   }


这几种都是WPF for win中使用的,希望能对你有所帮助。

链接:http://www.cnblogs.com/guozk/archive/2011/08/17/2142812.html

你可能感兴趣的:(WPF,Canvas转图片,Canvas转文本文件,Canvas转xps文件)