WPF把Canvas另存为
由于wpf的UI使用xaml来表达的,所以我们们可利用这个优点,把WPF中的xaml元素另存为各样的文件,在很多时候我们都不须要这样的操作。把xaml保存为图片、字符串、XPS等等。这里我写了一些方法,以供大家参考.
注意:以下保存操作前,一定要确保参数中的canvas有高和宽。
1.把canvas保存为文本文件
1: using System.Windows.Markup;
2: using System.IO;
1: public void Export(Uri path, Canvas surface)
2: {
3: if (path == null) return;
4: if (surface == null) return;
5:
6: string xaml = XamlWriter.Save(surface);
7: File.WriteAllText(path.LocalPath, xaml);
8: }
2.把canvas保存为xps文件,xps命名空间在ReachFramework.dll中
1: using System.IO.Packaging;
2: using System.Windows.Xps;
3: using System.Windows.Xps.Packaging;
4: using System.IO;
1: public void Export(Uri path, Canvas surface)
2: {
3: if (path == null) return;
4:
5: Transform transform = surface.LayoutTransform;
6: surface.LayoutTransform = null;
7:
8: Size size = new Size(surface.Width, surface.Height);
9: surface.Measure(size);
10: surface.Arrange(new Rect(size));
11:
12: Package package = Package.Open(path.LocalPath, FileMode.Create);
13: XpsDocument doc = new XpsDocument(package);
14: XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc);
15: writer.Write(surface);
16: doc.Close();
17: package.Close();
18:
19: surface.LayoutTransform = transform;
20: }
3.把canvas保存为图片
1: public void ExportToPng(Uri path, Canvas surface)
2: {
3: if (path == null) return;
4:
5: Transform transform = surface.LayoutTransform;
6: surface.LayoutTransform = null;
7:
8: Size size = new Size(surface.Width, surface.Height);
9: surface.Measure(size);
10: surface.Arrange(new Rect(size));
11:
12: RenderTargetBitmap renderBitmap =
13: new RenderTargetBitmap(
14: (int)size.Width,
15: (int)size.Height,
16: 96d,
17: 96d,
18: PixelFormats.Pbgra32);
19: renderBitmap.Render(surface);
20:
21: using (FileStream outStream = new FileStream(path.LocalPath, FileMode.Create))
22: {
23: PngBitmapEncoder encoder = new PngBitmapEncoder();
24: encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
25: encoder.Save(outStream);
26: }
27: surface.LayoutTransform = transform;
28: }
结束语:
这几种都是WPF for win中使用的,希望能对你有所帮助。