UCImage.xaml.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. using MeterVision.Patch;
  2. using MeterVision.Single;
  3. using Ookii.Dialogs.Wpf;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.ComponentModel;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using System.Windows;
  12. using System.Windows.Controls;
  13. using System.Windows.Data;
  14. using System.Windows.Documents;
  15. using System.Windows.Input;
  16. using System.Windows.Media;
  17. using System.Windows.Media.Imaging;
  18. using System.Windows.Navigation;
  19. //using System.Windows.Shapes;
  20. namespace MeterVision.UC
  21. {
  22. /// <summary>
  23. /// UCImage1.xaml 的交互逻辑
  24. /// </summary>
  25. public partial class UCImage : UserControl, INotifyPropertyChanged
  26. {
  27. private double zoomFactor = 1.0;
  28. private double rotationAngle = 0;
  29. private Point? dragStartPoint; // 用于记录鼠标按下的位置
  30. // Properties to bind to the XAML
  31. public double ZoomFactor
  32. {
  33. get => zoomFactor;
  34. set
  35. {
  36. zoomFactor = value;
  37. ApplyTransforms();
  38. }
  39. }
  40. public double RotationAngle
  41. {
  42. get => rotationAngle;
  43. set
  44. {
  45. rotationAngle = value;
  46. ApplyTransforms();
  47. }
  48. }
  49. public event PropertyChangedEventHandler PropertyChanged;
  50. protected void OnPropertyChanged(string propertyName)
  51. {
  52. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  53. }
  54. // 定义依赖属性 ImageSource,用于绑定图片路径
  55. public static readonly DependencyProperty ImageSourceProperty =
  56. DependencyProperty.Register("ImageSource", typeof(string), typeof(UCImage), new PropertyMetadata(null, OnImageSourceChanged));
  57. public string ImageSource
  58. {
  59. get => (string)GetValue(ImageSourceProperty);
  60. set => SetValue(ImageSourceProperty, value);
  61. }
  62. // 在 UCImage 类中添加一个私有字段
  63. private bool _loadedEventSubscribed = false;
  64. // 当 ImageSource 发生变化时,更新 Image 控件的源
  65. private static void OnImageSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  66. {
  67. var ucImage = d as UCImage;
  68. if (ucImage != null && e.NewValue is string imagePath && File.Exists(imagePath))
  69. {
  70. ucImage.pnlImageCtl.Visibility = Visibility.Visible;
  71. ucImage.zoomFactor = 1.0;
  72. ucImage.rotationAngle = 0;
  73. // 将图片路径转换为 BitmapImage
  74. ucImage.imgViewer.Source = new BitmapImage(new Uri(imagePath, UriKind.RelativeOrAbsolute));
  75. // 使用 Dispatcher 延迟调用
  76. //ucImage.Dispatcher.BeginInvoke(new Action(() =>
  77. //{
  78. // ucImage.CalculateInitialZoomFactor();
  79. //}), System.Windows.Threading.DispatcherPriority.ApplicationIdle);
  80. // 订阅 imgViewer 的 Loaded 事件
  81. if (!ucImage._loadedEventSubscribed)
  82. {
  83. ucImage._loadedEventSubscribed = true;
  84. ucImage.imgViewer.Loaded += (sender, args) =>
  85. {
  86. ucImage.imgViewer.Loaded -= (s, a) => { };
  87. ucImage.CalculateInitialZoomFactor();
  88. ucImage._loadedEventSubscribed = false; // 重置标志位以便下次使用
  89. };
  90. }
  91. }
  92. else
  93. {
  94. ucImage.imgViewer.Source = null;
  95. ucImage.pnlImageCtl.Visibility = Visibility.Collapsed;
  96. }
  97. }
  98. private string _imageName;
  99. public string ImageName
  100. {
  101. get => _imageName;
  102. set
  103. {
  104. if (_imageName != value)
  105. {
  106. _imageName = value;
  107. OnPropertyChanged(nameof(ImageName));
  108. }
  109. }
  110. }
  111. public UCImage()
  112. {
  113. InitializeComponent();
  114. this.DataContext = this;
  115. }
  116. private void ZoomIn_Click(object sender, RoutedEventArgs e)
  117. {
  118. // 增加缩放因子
  119. ZoomFactor *= 1.2;
  120. }
  121. private void ZoomOut_Click(object sender, RoutedEventArgs e)
  122. {
  123. // 减小缩放因子
  124. if (zoomFactor > 0.1) // 防止缩放因子过小
  125. {
  126. ZoomFactor /= 1.2;
  127. }
  128. }
  129. private void ZoomFit_Click(object sender, RoutedEventArgs e)
  130. {
  131. CalculateInitialZoomFactor();
  132. }
  133. private void RotateLeft_Click(object sender, RoutedEventArgs e)
  134. {
  135. // 向左旋转
  136. RotationAngle -= 90;
  137. }
  138. private void RotateRight_Click(object sender, RoutedEventArgs e)
  139. {
  140. // 向右旋转
  141. RotationAngle += 90;
  142. }
  143. private void ApplyTransforms()
  144. {
  145. // Ensure the zoom factor stays within reasonable bounds
  146. if (ZoomFactor < 0.1) ZoomFactor = 0.1;
  147. if (ZoomFactor > 10.0) ZoomFactor = 10.0;
  148. // Create a ScaleTransform to apply the zoom
  149. ScaleTransform scaleTransform = new ScaleTransform(ZoomFactor, ZoomFactor);
  150. // Create a RotateTransform to apply the rotation
  151. RotateTransform rotateTransform = new RotateTransform(RotationAngle);
  152. // Combine the scale and rotation transforms
  153. TransformGroup transformGroup = new TransformGroup();
  154. transformGroup.Children.Add(scaleTransform);
  155. transformGroup.Children.Add(rotateTransform);
  156. // Apply the combined transform to the image
  157. imgViewer.LayoutTransform = transformGroup;
  158. // Center the image in the ScrollViewer
  159. CenterImageInScrollViewer();
  160. }
  161. // Center the image in the ScrollViewer
  162. private void CenterImageInScrollViewer()
  163. {
  164. if (scrollViewer != null && imgViewer != null)
  165. {
  166. // Calculate the center of the image
  167. double imageWidth = imgViewer.ActualWidth * ZoomFactor;
  168. double imageHeight = imgViewer.ActualHeight * ZoomFactor;
  169. // Calculate the center of the ScrollViewer
  170. double scrollViewerWidth = scrollViewer.ViewportWidth;
  171. double scrollViewerHeight = scrollViewer.ViewportHeight;
  172. // Calculate the horizontal and vertical offsets to center the image
  173. double horizontalOffset = (imageWidth - scrollViewerWidth) / 2;
  174. double verticalOffset = (imageHeight - scrollViewerHeight) / 2;
  175. // Set the scroll position to center the image
  176. scrollViewer.ScrollToHorizontalOffset(horizontalOffset > 0 ? horizontalOffset : 0);
  177. scrollViewer.ScrollToVerticalOffset(verticalOffset > 0 ? verticalOffset : 0);
  178. }
  179. }
  180. private void ScrollViewer_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
  181. {
  182. if (Keyboard.Modifiers == ModifierKeys.Control)
  183. {
  184. if (e.Delta > 0)
  185. {
  186. zoomFactor *= 1.2; // Increase zoom factor by 20%
  187. }
  188. else
  189. {
  190. zoomFactor /= 1.2; // Decrease zoom factor by 20%
  191. }
  192. //e.Handled = true;
  193. }
  194. }
  195. // 当用户按下鼠标左键时,记录按下的位置
  196. private void Image_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
  197. {
  198. dragStartPoint = e.GetPosition(scrollViewer);
  199. }
  200. // 当用户拖动鼠标时,根据鼠标的移动调整 ScrollViewer 的滚动位置
  201. private void Image_PreviewMouseMove(object sender, MouseEventArgs e)
  202. {
  203. if (dragStartPoint.HasValue && e.LeftButton == MouseButtonState.Pressed)
  204. {
  205. Point currentPoint = e.GetPosition(scrollViewer);
  206. Vector delta = Point.Subtract(dragStartPoint.Value, currentPoint);
  207. // 调整 ScrollViewer 的滚动位置
  208. scrollViewer.ScrollToHorizontalOffset(scrollViewer.HorizontalOffset + delta.X);
  209. scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset + delta.Y);
  210. // 更新拖动起点为当前点,以防止累积偏移
  211. dragStartPoint = currentPoint;
  212. }
  213. }
  214. private void Image_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
  215. {
  216. dragStartPoint = null;
  217. }
  218. // 计算初始缩放比例,使得图片正好适应 ScrollViewer 的视口
  219. public void CalculateInitialZoomFactor()
  220. {
  221. if (scrollViewer != null && imgViewer != null)
  222. {
  223. // 获取 ScrollViewer 的视口尺寸
  224. double scrollViewerWidth = scrollViewer.ViewportWidth;
  225. double scrollViewerHeight = scrollViewer.ViewportHeight;
  226. // 获取图片的实际尺寸
  227. double imageWidth = imgViewer.ActualWidth;
  228. double imageHeight = imgViewer.ActualHeight;
  229. // 如果图片还没有加载完成,等待加载完成后再次尝试计算
  230. if (double.IsNaN(imageWidth) || double.IsNaN(imageHeight))
  231. {
  232. //imgViewer.Loaded += (s, ev) => CalculateInitialZoomFactor();
  233. return;
  234. }
  235. // 计算水平和垂直方向的缩放比例
  236. double scaleX = scrollViewerWidth / imageWidth;
  237. double scaleY = scrollViewerHeight / imageHeight;
  238. // 选择较小的缩放比例,以确保图片完全适应 ScrollViewer
  239. double initialZoomFactor = Math.Min(scaleX, scaleY);
  240. // 确保缩放比例不会小于 0.1 或大于 10.0
  241. if (initialZoomFactor < 0.1) initialZoomFactor = 0.1;
  242. if (initialZoomFactor > 10.0) initialZoomFactor = 10.0;
  243. // 应用初始缩放比例
  244. ZoomFactor = initialZoomFactor;
  245. // 中心化图片
  246. CenterImageInScrollViewer();
  247. }
  248. }
  249. public void ImageZoom(bool zoomIn, MouseWheelEventArgs e)
  250. {
  251. if (zoomIn)
  252. {
  253. ZoomFactor *= 1.1; // Zoom in
  254. }
  255. else
  256. {
  257. ZoomFactor /= 1.1; // Zoom out
  258. }
  259. Point mousePosition = e.GetPosition(imgViewer);
  260. double prevZoomFactor = 1 / ZoomFactor;
  261. double offsetX = (mousePosition.X * ZoomFactor - mousePosition.X * prevZoomFactor) / prevZoomFactor;
  262. double offsetY = (mousePosition.Y * ZoomFactor - mousePosition.Y * prevZoomFactor) / prevZoomFactor;
  263. scrollViewer.ScrollToHorizontalOffset(scrollViewer.HorizontalOffset + offsetX);
  264. scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset + offsetY);
  265. }
  266. private void ImageSave_Click(object sender, RoutedEventArgs e)
  267. {
  268. if (imgViewer.Source != null)
  269. {
  270. ExportImage(imgViewer);
  271. }
  272. }
  273. private void ExportImage(Image imageControl)
  274. {
  275. if (imageControl.Source is BitmapImage bitmapImage)
  276. {
  277. try
  278. {
  279. // 1. 获取原始文件路径
  280. string sourcePath = bitmapImage.UriSource.LocalPath;
  281. if (string.IsNullOrEmpty(sourcePath) || !File.Exists(sourcePath))
  282. {
  283. MessageBox.Show("无法确定原始文件路径或文件不存在。");
  284. return;
  285. }
  286. // 2. 弹出保存对话框
  287. VistaSaveFileDialog saveFileDialog = new VistaSaveFileDialog
  288. {
  289. FileName = Path.GetFileName(sourcePath), // 默认文件名
  290. DefaultExt = Path.GetExtension(sourcePath),
  291. Filter = $"Image Files (*{Path.GetExtension(sourcePath)})|*{Path.GetExtension(sourcePath)}|All Files (*.*)|*.*"
  292. };
  293. if (saveFileDialog.ShowDialog() == true)
  294. {
  295. // 3. 直接复制文件
  296. File.Copy(sourcePath, saveFileDialog.FileName, true);
  297. //MessageBox.Show("图片导出成功。");
  298. }
  299. }
  300. catch (Exception ex)
  301. {
  302. MessageBox.Show($"导出失败: {ex.Message}");
  303. }
  304. }
  305. else
  306. {
  307. MessageBox.Show("Image控件中没有有效的图像。");
  308. }
  309. }
  310. ///////////////////////////////////////////////////////////////////////
  311. }
  312. }