Canvas另存

把canvas保存为文本文件:
  using System.Windows.Markup;
  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);
  }


把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;
  }

你可能感兴趣的:(Canvas另存)