日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

OxyPlot 导出图片及 WPF 元素导出为图片的方法

發布時間:2023/12/4 asp.net 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 OxyPlot 导出图片及 WPF 元素导出为图片的方法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

OxyPlot 導出圖片及 WPF 元素導出為圖片的方法

目錄

OxyPlot 導出圖片及 WPF 元素導出為圖片的方法

一、OxyPlot 自帶導出方法

二、導出 WPF 界面元素的方法

三、通過附加屬性來使用

獨立觀察員 2022 年 2 月 26 日

最近有個需求,就是將?OxyPlot?圖形導出圖片。經過嘗試,本文記錄三種方法:1、OxyPlot?自帶導出方法;2、網上找的導出?WPF?界面元素的方法;3、基于方法 2 的附加屬性調用方式。下面將逐一介紹。

一、OxyPlot 自帶導出方法

同事說這個用 OxyPlot 官方提供的導出方法即可,我在 Demo 中試了一下,是可以的,代碼如下:

/// <summary> /// 曲線數據源(OxyPlot) /// </summary> public PlotModel PlotModel { get; set; } = new PlotModel();ExportPngCmd ??= new RelayCommand(o => true, async o => {var pngExporter = new PngExporter { Width = (int)PlotModel.Width, Height = (int)PlotModel.Height, };//string exportPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Export");string exportPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "Export");if (!Directory.Exists(exportPath)){Directory.CreateDirectory(exportPath);}pngExporter.ExportToFile(PlotModel, Path.Combine(exportPath, $"{DateTime.Now:yyyyMMdd_HHmmss}.png"));await ConfirmBoxHelper.ShowMessage(DialogVm, "導出完成", 3); });

各種導出方法可以在 OxyPlot 官方文檔(https://oxyplot.readthedocs.io/en/latest/export/index.html)中查看

這里用到的是導出到 PNG 文件的方法,不過用的 NuGet 包最新版(2.1.0)中,PngExporter 中并沒有 Background 屬性:

所以如果圖表沒有設置背景色的話,導出背景為透明的,可以設置上:

PlotModel.Background = OxyColor.Parse("#FFFFFF");

總的來說,這個方法簡單快捷,而且對 MVVM 友好。不過也有缺點,就是如果有些元素(比如說標題、坐標軸文字)不是使用 OxyPlot?圖表控件來生成的話,則導出的圖片就不會包含它們了:

我在實際項目中確實遇到了這個問題,所以需要尋找其它方法,我們接著看。

二、導出?WPF?界面元素的方法

首先給出能夠導出任意 WPF 界面元素(FrameworkElement)為圖片的方法,來源于網絡,地址在方法注釋中已給出,略作修改,代碼如下:

using System; using System.IO; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging;namespace WPFTemplateLib.WpfHelpers {/// <summary>/// 導出圖片幫助類/// </summary>public class ExportPicHelper{/// <summary>/// 保存為圖片/// (修改自:https://blog.csdn.net/dhl11/article/details/108621634)/// </summary>/// <param name="frameworkElement"> 可視化元素,可以是 Grid、StackPanel 等類型的所有可視化元素 </param>/// <param name="filePath"> 文件路徑 </param>/// <param name="errorMsg"> 錯誤消息 </param>/// <returns> 是否成功 </returns>public static bool SaveToImage(FrameworkElement frameworkElement, string filePath, out string errorMsg){try{errorMsg = string.Empty;FileStream fs = new FileStream(filePath, FileMode.Create);RenderTargetBitmap bmp = new RenderTargetBitmap((int)frameworkElement.ActualWidth,(int)frameworkElement.ActualHeight,1 / 96, 1 / 96, PixelFormats.Default);bmp.Render(frameworkElement);BitmapEncoder encoder = new TiffBitmapEncoder();encoder.Frames.Add(BitmapFrame.Create(bmp));encoder.Save(fs);fs.Close();return true;}catch (Exception ex){Console.WriteLine($" 保存圖片異常:{ex}");errorMsg = ex.Message;return false;}}} }

用這個方法首先要給界面元素起個名字,我這里給圖表區用戶控件元素起了個 “Plot” 名稱:

這樣在后臺代碼中就可以用來導出了:

private void ExportPicBtn_OnClick(object sender, RoutedEventArgs e) {ExportPicture(Plot); }/// <summary> /// 導出圖片 /// </summary> /// <param name="element">xaml 里面的某個可視化元素對象 </param> private void ExportPicture(FrameworkElement element) {SaveFileDialog saveFileDialog = new SaveFileDialog{Filter = "PNG 文件 (*.png)|*.png|JPG 文件 (*.jpg)|*.jpg|BMP 文件 (*.bmp)|*.bmp|GIF 文件 (*.gif)|*.gif|TIF 文件 (*.tif)|*.tif"};if (saveFileDialog.ShowDialog() == true){string dir = System.IO.Path.GetDirectoryName(saveFileDialog.FileName);if (!Directory.Exists(dir)){Directory.CreateDirectory(dir);}string filePath = saveFileDialog.FileName;if (File.Exists(filePath)){File.Delete(filePath);}bool success = ExportPicHelper.SaveToImage(element, filePath, out string errorMsg);if (success){MessageBox.Show($"導出成功");}else{MessageBox.Show($" 導出失敗 {errorMsg}");}} }

可以看到想要導出的內容都導出成功了:

優點是顯而易見的,缺點就是導出邏輯要寫在后臺代碼中,對 MVVM 模式不友好。下面來看看本人修改的使用附加屬性的方案,嘗試解決這個問題。

三、通過附加屬性來使用

還是先給出代碼:

using System; using System.IO; using System.Windows; using WPFTemplateLib.WpfHelpers;namespace WPFTemplateLib.Attached {/// <summary>/// 導出圖片附加屬性類/// </summary>public class ExportPicAttached : DependencyObject{#region 是否開始導出public static bool GetIsExporting(DependencyObject obj){return (bool)obj.GetValue(IsExportingProperty);}public static void SetIsExporting(DependencyObject obj, bool value){obj.SetValue(IsExportingProperty, value);}/// <summary>/// 是否正在導出(運行時設置為 true 則將附加的元素導出為圖片)/// </summary>public static readonly DependencyProperty IsExportingProperty =DependencyProperty.RegisterAttached("IsExporting", typeof(bool), typeof(ExportPicAttached),new PropertyMetadata(false, OnIsExportingValueChanged));private static void OnIsExportingValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e){FrameworkElement element = d as FrameworkElement;if (element == null)return;if ((e.NewValue as bool?) == false)return;try{string exportPath = GetExportPath(d);if (string.IsNullOrEmpty(exportPath)){exportPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),"Export");}if (!Directory.Exists(exportPath)){Directory.CreateDirectory(exportPath);}string filePath = Path.Combine(exportPath, $"{DateTime.Now:yyyyMMddHHmmss}.png");bool success = ExportPicHelper.SaveToImage(element, filePath, out string errorMsg);if (success){MessageBox.Show($"導出成功");}else{Console.WriteLine($" 導出失敗:{errorMsg}");MessageBox.Show($" 導出失敗 {errorMsg}");}}catch (Exception ex){Console.WriteLine($" 導出異常:{ex}");MessageBox.Show($" 導出異常:{ex.Message}");}finally{// 此處設置為 false 沒什么用,還是需要業務層在設置為 true 前先設置為 false 才行。SetIsExporting(d, false);}}#endregion#region 導出文件夾public static string GetExportPath(DependencyObject obj){return (string)obj.GetValue(ExportPathProperty);}public static void SetExportPath(DependencyObject obj, string value){obj.SetValue(ExportPathProperty, value);}/// <summary>/// 導出文件夾路徑/// </summary>public static readonly DependencyProperty ExportPathProperty =DependencyProperty.RegisterAttached("ExportPath", typeof(string), typeof(ExportPicAttached), new PropertyMetadata(string.Empty));#endregion} }

ExportPicAttached 類中包含兩個附加屬性,一個是導出文件夾路徑 ExportPath,一個是是否開始導出 IsExporting。當 IsExporting 被設置為 true 則開始導出,如果導出文件夾路徑沒被設定,則導出到桌面文件夾,然后就是調用方案二中出現的 ExportPicHelper.SaveToImage 方法。

使用方法就是在要導出的元素上設置上這兩個附加屬性,然后把值進行綁定:

在 ViewModel 中,先設定導出路徑,然后把 IsExporting 置為 true 即可開始導出:

也是能正常導出的:

這個方案結合了前兩個方案的優點,既能導出所有想要的內容,又對 MVVM 友好。

缺點就是導出的控制有點奇怪,需要先將 IsExporting 置為 false,不然第二次就導出不了了。嘗試了在附加屬性邏輯中自動置為 false,但是好像值傳遞不到 VM 中的相關綁定屬性中,有了解解決方法的朋友們請不吝賜教。

全文完,感謝閱讀,祝大家天天開心。

WPF

讓 WPF 的 RadioButton 支持再次點擊取消選中的功能

WPF DataGrid 如何將被選中行帶到視野中

WPF 觸屏事件后觸發鼠標事件的問題及 DataGrid 誤觸問題

WPF DataGrid 通過自定義表頭模擬首行固定

WPF ComboBox 使用 ResourceBinding 動態綁定資源鍵并支持語言切換

【翻譯】WPF 中附加行為的介紹 Introduction to Attached Behaviors in WPF

WPF 使用 Expression Design 畫圖導出及使用 Path 畫圖

WPF?MVVM?彈框之等待框

解決 WPF 綁定集合后數據變動界面卻不更新的問題(使用 ObservableCollection)

WPF?消息框?TextBox?綁定新數據時讓光標和滾動條跳到最下面

真?WPF?按鈕拖動和調整大小

WPF?MVVM?模式下的彈窗

WPF?讓一組 Button 實現?RadioButton?的當前樣式效果

WPF?原生綁定和命令功能使用指南

WPF?用戶控件的自定義依賴屬性在?MVVM?模式下的使用備忘

在WPF的MVVM模式中使用OCX組件

第三方庫使用

WPF 表格控件 ReoGrid 的簡單使用

OxyPlot.WPF 公共屬性一覽

OxyPlot.Wpf 圖表控件使用備忘

總結

以上是生活随笔為你收集整理的OxyPlot 导出图片及 WPF 元素导出为图片的方法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。