WPF把Canvas保存为图片,文本文件,xps文件
由于wpf的UI使用xaml来表达的,所以我们们可利用这个优点,把WPF中的xaml元素另存为各样的文件,在很多时候我们都不须要这样的操作。把xaml保存为图片、字符串、XPS等等。这里我写了一些方法,以供大家参考.。
注意:以下保存操作前,一定要确保参数中的canvas有高和宽。
1.把canvas保存为文本文件
1 2 3 4 5 6 7 | 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中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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保存为图片
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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; } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?