RecordLineChart.xaml.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. using Microsoft.Win32;
  2. using ScottPlot;
  3. using ScottPlot.Plottables;
  4. using ScottPlot.WPF;
  5. using SWRIS.Dtos;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Windows;
  10. using System.Windows.Controls;
  11. namespace SWRIS.Controls
  12. {
  13. /// <summary>
  14. /// 动态折线图用户控件(基于 ScottPlot.WPF 的高性能版本)
  15. /// </summary>
  16. public partial class RecordLineChart : UserControl
  17. {
  18. private readonly Color[] _colors = new Color[] {
  19. new Color("#70a1d7"), new Color("#a1de93"),
  20. new Color("#f7f48b"), new Color("#f47c7c"),
  21. new Color("#c264fe"), new Color("#00fff5"),
  22. new Color("#f8b195"), new Color("#7a08fa") };
  23. private const double MAXDAMAGE = 128; // 最大损伤值
  24. private SignalXY[] _sensorSignals;
  25. private SignalXY _mergeSignal;
  26. private Scatter[] _makerScatters;
  27. private AxisLimits _axisLimit;
  28. public RecordLineChart()
  29. {
  30. InitializeComponent();
  31. InitializePlot();
  32. }
  33. private void InitializePlot()
  34. {
  35. WpfPlot.Menu?.Clear();
  36. WpfPlot.Menu.Add("保存图片", pt =>
  37. {
  38. OpenSaveImageDialog(pt);
  39. });
  40. WpfPlot.Menu.Add("重置视图", pt =>
  41. {
  42. WpfPlot.Plot.Axes.SetLimits(_axisLimit);
  43. WpfPlot.Refresh();
  44. });
  45. var plot = WpfPlot.Plot;
  46. plot.Clear();
  47. plot.DataBackground.Color = Colors.Transparent;
  48. plot.FigureBackground.Color = Colors.Transparent;
  49. plot.Grid.MajorLineColor = new Color(59, 59, 123).WithOpacity(0.6);
  50. plot.Grid.XAxis.TickLabelStyle.ForeColor = new Color(151, 166, 212);
  51. plot.Grid.YAxis.TickLabelStyle.ForeColor = new Color(151, 166, 212);
  52. plot.Grid.XAxis.FrameLineStyle.Color = new Color(53, 53, 112);
  53. plot.Grid.XAxis.FrameLineStyle.Width = 3;
  54. plot.Grid.YAxis.FrameLineStyle.Color = new Color(53, 53, 112);
  55. plot.Grid.YAxis.FrameLineStyle.Width = 3;
  56. plot.Grid.XAxis.MajorTickStyle.Color = new Color(53, 53, 112);
  57. plot.Grid.XAxis.MajorTickStyle.Width = 1;
  58. plot.Grid.YAxis.MajorTickStyle.Color = new Color(53, 53, 112);
  59. plot.Grid.YAxis.MajorTickStyle.Width = 1;
  60. plot.Grid.YAxis.MinorTickStyle.Color = new Color(53, 53, 112);
  61. plot.Grid.XAxis.MinorTickStyle.Color = new Color(53, 53, 112);
  62. plot.Axes.Hairline(false);
  63. }
  64. public void AddDataPoints((double[] Positions, ushort[,] Damages) dataPoints, int[] inUseSensors, List<DamageDto> alertDamages)
  65. {
  66. if (dataPoints.Damages == null || dataPoints.Positions == null)
  67. {
  68. return;
  69. }
  70. if (inUseSensors == null || inUseSensors.Length == 0)
  71. {
  72. return;
  73. }
  74. int sensorCount = dataPoints.Damages.GetLength(0);
  75. int sampleCount = dataPoints.Damages.GetLength(1);
  76. double startPoint = dataPoints.Positions.First();
  77. double endPoint = dataPoints.Positions.Last();
  78. int enabledSensorCount = inUseSensors.Length;
  79. double[] mergeData = new double[sampleCount];
  80. // 先计算所有传感器的合并数据
  81. for (int j = 0; j < sampleCount; j++)
  82. {
  83. ushort totalValue = 0;
  84. foreach (var i in inUseSensors)
  85. {
  86. totalValue += dataPoints.Damages[i - 1, j];
  87. }
  88. // 计算平均值并赋值
  89. mergeData[j] = totalValue / enabledSensorCount;
  90. }
  91. AddMaker(dataPoints.Positions, mergeData, alertDamages);
  92. // 然后处理每个传感器的数据
  93. int enabledSensorIndex = 0;
  94. _sensorSignals = new SignalXY[enabledSensorCount];
  95. for (int i = 0; i < sensorCount; i++)
  96. {
  97. if (inUseSensors.Contains(i + 1))
  98. {
  99. ushort[] sensorData = new ushort[sampleCount];
  100. for (int j = 0; j < sampleCount; j++)
  101. {
  102. sensorData[j] = dataPoints.Damages[i, j];
  103. }
  104. var signalPlot = WpfPlot.Plot.Add.SignalXY(dataPoints.Positions, sensorData);
  105. signalPlot.LineWidth = 1;
  106. signalPlot.Color = _colors[i];
  107. signalPlot.IsVisible = false;
  108. _sensorSignals[enabledSensorIndex] = signalPlot;
  109. enabledSensorIndex++;
  110. }
  111. }
  112. _mergeSignal = WpfPlot.Plot.Add.SignalXY(dataPoints.Positions, mergeData);
  113. _mergeSignal.LineWidth = 2;
  114. _mergeSignal.Color = new Color("#9664F3");
  115. //差值
  116. double offset = (endPoint - startPoint) * 0.1;
  117. // 动态计算Y轴最大值
  118. double yMax = mergeData.Length > 0 ? mergeData.Max() : MAXDAMAGE;
  119. double yMargin = yMax * 0.1;
  120. if (yMax == 0) yMargin = 10;
  121. _axisLimit = new AxisLimits(startPoint - offset, endPoint + offset, 0, yMax + yMargin);
  122. WpfPlot.Plot.Axes.SetLimits(_axisLimit);
  123. WpfPlot.Refresh();
  124. }
  125. public void SignalPlotVisible(int id, bool isVisible)
  126. {
  127. if (id > _sensorSignals.Length) return;
  128. if (id == 0)
  129. {
  130. _mergeSignal.IsVisible = isVisible;
  131. foreach (var maker in _makerScatters)
  132. {
  133. maker.IsVisible = isVisible;
  134. }
  135. }
  136. else
  137. {
  138. _sensorSignals[id - 1].IsVisible = isVisible;
  139. }
  140. WpfPlot.Refresh();
  141. }
  142. private void AddMaker(double[] dataPoints, double[] mergeData, List<DamageDto> alertDamages)
  143. {
  144. int markerCount = alertDamages.Count;
  145. _makerScatters = new Scatter[markerCount];
  146. for (int i = 0; i < markerCount; i++)
  147. {
  148. int index = FindNearestIndex(dataPoints, alertDamages[i].DamagePoint);
  149. if (index < 0 || index >= dataPoints.Length)
  150. continue;
  151. var marker = WpfPlot.Plot.Add.Scatter(dataPoints[index], mergeData[index]);
  152. marker.LineWidth = 0; // 不显示连线
  153. marker.MarkerSize = 10;
  154. marker.MarkerShape = MarkerShape.OpenCircle;
  155. marker.MarkerLineWidth = 2;
  156. switch (alertDamages[i].DamageLevel)
  157. {
  158. case Enums.DamageLevel.Mild:
  159. marker.Color = Color.FromHex("#00FF78");
  160. break;
  161. case Enums.DamageLevel.Light:
  162. marker.Color = Color.FromHex("#FFF000");
  163. break;
  164. case Enums.DamageLevel.Moderate:
  165. marker.Color = Color.FromHex("#FF9400");
  166. break;
  167. case Enums.DamageLevel.Severe:
  168. marker.Color = Color.FromHex("#FF6C00");
  169. break;
  170. case Enums.DamageLevel.Critical:
  171. marker.Color = Color.FromHex("#FF0000");
  172. break;
  173. case Enums.DamageLevel.ExceededLimit:
  174. marker.Color = Color.FromHex("#FF008A");
  175. break;
  176. }
  177. _makerScatters[i] = marker;
  178. }
  179. }
  180. private int FindNearestIndex(double[] positions, double target)
  181. {
  182. if (positions == null || positions.Length == 0)
  183. return -1;
  184. int index = Array.BinarySearch(positions, target);
  185. // 如果找到精确匹配
  186. if (index >= 0)
  187. return index;
  188. // 如果没找到,BinarySearch 返回下一个更大元素的补码
  189. int largerIndex = ~index;
  190. // 处理边界情况
  191. if (largerIndex == 0)
  192. return 0;
  193. if (largerIndex == positions.Length)
  194. return positions.Length - 1;
  195. // 比较左右两个元素哪个更接近
  196. double diffLeft = Math.Abs(positions[largerIndex - 1] - target);
  197. double diffRight = Math.Abs(positions[largerIndex] - target);
  198. return diffLeft < diffRight ? largerIndex - 1 : largerIndex;
  199. }
  200. public void OpenSaveImageDialog(Plot plot)
  201. {
  202. SaveFileDialog saveFileDialog = new SaveFileDialog
  203. {
  204. Filter = "PNG Files (*.png)|*.png|JPEG Files (*.jpg, *.jpeg)|*.jpg;*.jpeg|BMP Files (*.bmp)|*.bmp|WebP Files (*.webp)|*.webp|SVG Files (*.svg)|*.svg|All files (*.*)|*.*"
  205. };
  206. bool? flag = saveFileDialog.ShowDialog();
  207. if (flag.HasValue && flag == true && !string.IsNullOrEmpty(saveFileDialog.FileName))
  208. {
  209. ImageFormat format;
  210. try
  211. {
  212. format = ImageFormats.FromFilename(saveFileDialog.FileName);
  213. }
  214. catch (ArgumentException)
  215. {
  216. MessageBox.Show("Unsupported image file format", "ERROR", MessageBoxButton.OK, MessageBoxImage.Hand);
  217. return;
  218. }
  219. try
  220. {
  221. PixelSize size = plot.RenderManager.LastRender.FigureRect.Size;
  222. plot.Save(saveFileDialog.FileName, (int)size.Width, (int)size.Height, format);
  223. }
  224. catch (Exception)
  225. {
  226. MessageBox.Show("Image save failed", "ERROR", MessageBoxButton.OK, MessageBoxImage.Hand);
  227. }
  228. }
  229. }
  230. }
  231. }