DlgImage.xaml.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. using Ookii.Dialogs.Wpf;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Runtime.InteropServices;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows;
  10. using System.Windows.Controls;
  11. using System.Windows.Data;
  12. using System.Windows.Documents;
  13. using System.Windows.Input;
  14. using System.Windows.Interop;
  15. using System.Windows.Media;
  16. using System.Windows.Media.Imaging;
  17. namespace MV485.Dlg
  18. {
  19. /// <summary>
  20. /// DlgImage.xaml 的交互逻辑
  21. /// </summary>
  22. public partial class DlgImage : Window
  23. {
  24. [DllImport("user32.dll")]
  25. private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
  26. [DllImport("user32.dll")]
  27. private static extern bool DeleteMenu(IntPtr hMenu, uint uPosition, uint uFlags);
  28. private const uint SC_MINIMIZE = 0xF020;
  29. private const uint MF_BYCOMMAND = 0x00000000;
  30. private double zoomFactor = 1.0;
  31. private double rotationAngle = 0;
  32. private Point? dragStartPoint; // 用于记录鼠标按下的位置
  33. private string _imageSourcePath;
  34. public string ImageSourcePath => _imageSourcePath;
  35. public DlgImage(string imageSourcePath)
  36. {
  37. InitializeComponent();
  38. //int width = CfginiItem.GetConfigItem().DialogImageSize_Width;
  39. //int height = CfginiItem.GetConfigItem().DialogImageSize_Height;
  40. //if (width != 0 && height != 0)
  41. //{
  42. // this.Width = width;
  43. // this.Height = height;
  44. //}
  45. _imageSourcePath = imageSourcePath;
  46. if (File.Exists(imageSourcePath))
  47. {
  48. imgViewer.Source = new BitmapImage(new Uri(imageSourcePath, UriKind.RelativeOrAbsolute));
  49. }
  50. DataContext = this;
  51. }
  52. // 鼠标点击外部时关闭窗口
  53. private void OnMouseDownOutside(object sender, MouseButtonEventArgs e)
  54. {
  55. //this.Close();
  56. }
  57. private void ImgWindow_Deactivated(object sender, EventArgs e)
  58. {
  59. //throw new NotImplementedException();
  60. //this.Close();
  61. }
  62. private void DisableMinimizeButton()
  63. {
  64. if (this.IsLoaded)
  65. {
  66. var helper = new WindowInteropHelper(this);
  67. var menu = GetSystemMenu(helper.Handle, false);
  68. if (menu != IntPtr.Zero)
  69. {
  70. DeleteMenu(menu, SC_MINIMIZE, MF_BYCOMMAND);
  71. }
  72. }
  73. }
  74. public double ZoomFactor
  75. {
  76. get => zoomFactor;
  77. set
  78. {
  79. zoomFactor = value;
  80. ApplyTransforms();
  81. }
  82. }
  83. public double RotationAngle
  84. {
  85. get => rotationAngle;
  86. set
  87. {
  88. rotationAngle = value;
  89. ApplyTransforms();
  90. }
  91. }
  92. private void ZoomIn_Click(object sender, RoutedEventArgs e)
  93. {
  94. ZoomFactor *= 1.2; // Increase zoom factor by 20%
  95. }
  96. // Zoom out button click event
  97. private void ZoomOut_Click(object sender, RoutedEventArgs e)
  98. {
  99. ZoomFactor /= 1.2; // Decrease zoom factor by 20%
  100. }
  101. private void ZoomFit_Click(object sender, RoutedEventArgs e)
  102. {
  103. CalculateInitialZoomFactor();
  104. }
  105. private void RotateLeft_Click(object sender, RoutedEventArgs e)
  106. {
  107. RotationAngle -= 90; // Rotate 90 degrees counterclockwise
  108. }
  109. // Rotate right button click event
  110. private void RotateRight_Click(object sender, RoutedEventArgs e)
  111. {
  112. RotationAngle += 90; // Rotate 90 degrees clockwise
  113. }
  114. private void ApplyTransforms()
  115. {
  116. // Ensure the zoom factor stays within reasonable bounds
  117. if (ZoomFactor < 0.1) ZoomFactor = 0.1;
  118. if (ZoomFactor > 10.0) ZoomFactor = 10.0;
  119. // Create a ScaleTransform to apply the zoom
  120. ScaleTransform scaleTransform = new ScaleTransform(ZoomFactor, ZoomFactor);
  121. // Create a RotateTransform to apply the rotation
  122. RotateTransform rotateTransform = new RotateTransform(RotationAngle);
  123. // Combine the scale and rotation transforms
  124. TransformGroup transformGroup = new TransformGroup();
  125. transformGroup.Children.Add(scaleTransform);
  126. transformGroup.Children.Add(rotateTransform);
  127. // Apply the combined transform to the image
  128. imgViewer.LayoutTransform = transformGroup;
  129. // Center the image in the ScrollViewer
  130. CenterImageInScrollViewer();
  131. }
  132. // Center the image in the ScrollViewer
  133. private void CenterImageInScrollViewer()
  134. {
  135. if (scrollViewer != null && imgViewer != null)
  136. {
  137. // Calculate the center of the image
  138. double imageWidth = imgViewer.ActualWidth * ZoomFactor;
  139. double imageHeight = imgViewer.ActualHeight * ZoomFactor;
  140. // Calculate the center of the ScrollViewer
  141. double scrollViewerWidth = scrollViewer.ViewportWidth;
  142. double scrollViewerHeight = scrollViewer.ViewportHeight;
  143. // Calculate the horizontal and vertical offsets to center the image
  144. double horizontalOffset = (imageWidth - scrollViewerWidth) / 2;
  145. double verticalOffset = (imageHeight - scrollViewerHeight) / 2;
  146. // Set the scroll position to center the image
  147. scrollViewer.ScrollToHorizontalOffset(horizontalOffset > 0 ? horizontalOffset : 0);
  148. scrollViewer.ScrollToVerticalOffset(verticalOffset > 0 ? verticalOffset : 0);
  149. }
  150. }
  151. private void ScrollViewer_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
  152. {
  153. if (Keyboard.Modifiers == ModifierKeys.Control)
  154. {
  155. if (e.Delta > 0)
  156. {
  157. zoomFactor *= 1.2; // Increase zoom factor by 20%
  158. }
  159. else
  160. {
  161. zoomFactor /= 1.2; // Decrease zoom factor by 20%
  162. }
  163. //e.Handled = true;
  164. }
  165. }
  166. private void Window_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
  167. {
  168. //按廉博要求,取消按control键
  169. //if (Keyboard.Modifiers == ModifierKeys.Control)
  170. //{
  171. if (e.Delta > 0)
  172. {
  173. ZoomFactor *= 1.1; // Zoom in
  174. }
  175. else
  176. {
  177. ZoomFactor /= 1.1; // Zoom out
  178. }
  179. // Optionally, center the zoom around the mouse cursor
  180. Point mousePosition = e.GetPosition(imgViewer);
  181. double prevZoomFactor = 1 / ZoomFactor;
  182. double offsetX = (mousePosition.X * ZoomFactor - mousePosition.X * prevZoomFactor) / prevZoomFactor;
  183. double offsetY = (mousePosition.Y * ZoomFactor - mousePosition.Y * prevZoomFactor) / prevZoomFactor;
  184. scrollViewer.ScrollToHorizontalOffset(scrollViewer.HorizontalOffset + offsetX);
  185. scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset + offsetY);
  186. //}
  187. }
  188. // 当用户按下鼠标左键时,记录按下的位置
  189. private void Image_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
  190. {
  191. dragStartPoint = e.GetPosition(scrollViewer);
  192. }
  193. // 当用户拖动鼠标时,根据鼠标的移动调整 ScrollViewer 的滚动位置
  194. private void Image_PreviewMouseMove(object sender, MouseEventArgs e)
  195. {
  196. if (dragStartPoint.HasValue && e.LeftButton == MouseButtonState.Pressed)
  197. {
  198. Point currentPoint = e.GetPosition(scrollViewer);
  199. Vector delta = Point.Subtract(dragStartPoint.Value, currentPoint);
  200. // 调整 ScrollViewer 的滚动位置
  201. scrollViewer.ScrollToHorizontalOffset(scrollViewer.HorizontalOffset + delta.X);
  202. scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset + delta.Y);
  203. // 更新拖动起点为当前点,以防止累积偏移
  204. dragStartPoint = currentPoint;
  205. }
  206. }
  207. // 当用户释放鼠标左键时,停止拖动
  208. private void Image_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
  209. {
  210. dragStartPoint = null;
  211. }
  212. private void Window_Loaded(object sender, RoutedEventArgs e)
  213. {
  214. DisableMinimizeButton();
  215. if (imgViewer.Source != null)
  216. {
  217. CalculateInitialZoomFactor();
  218. }
  219. }
  220. // 计算初始缩放比例,使得图片正好适应 ScrollViewer 的视口
  221. private void CalculateInitialZoomFactor()
  222. {
  223. if (scrollViewer != null && imgViewer != null)
  224. {
  225. // 获取 ScrollViewer 的视口尺寸
  226. double scrollViewerWidth = scrollViewer.ViewportWidth;
  227. double scrollViewerHeight = scrollViewer.ViewportHeight;
  228. // 获取图片的实际尺寸
  229. double imageWidth = imgViewer.ActualWidth;
  230. double imageHeight = imgViewer.ActualHeight;
  231. // 如果图片还没有加载完成,等待加载完成后再次尝试计算
  232. if (double.IsNaN(imageWidth) || double.IsNaN(imageHeight))
  233. {
  234. imgViewer.Loaded += (s, ev) => CalculateInitialZoomFactor();
  235. return;
  236. }
  237. // 计算水平和垂直方向的缩放比例
  238. double scaleX = scrollViewerWidth / imageWidth;
  239. double scaleY = scrollViewerHeight / imageHeight;
  240. // 选择较小的缩放比例,以确保图片完全适应 ScrollViewer
  241. double initialZoomFactor = Math.Min(scaleX, scaleY);
  242. // 确保缩放比例不会小于 0.1 或大于 10.0
  243. if (initialZoomFactor < 0.1) initialZoomFactor = 0.1;
  244. if (initialZoomFactor > 10.0) initialZoomFactor = 10.0;
  245. // 应用初始缩放比例
  246. ZoomFactor = initialZoomFactor;
  247. // 中心化图片
  248. CenterImageInScrollViewer();
  249. }
  250. }
  251. private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
  252. {
  253. }
  254. private void Window_Closed(object sender, EventArgs e)
  255. {
  256. //WindowState = "Maximized"
  257. if (WindowState != WindowState.Maximized)
  258. {
  259. int width = (int)this.Width;
  260. int height = (int)this.Height;
  261. string dialogSize = $"{width},{height}";
  262. //CfginiItem.GetConfigItem().DialogImageSize = dialogSize;
  263. }
  264. }
  265. private void ImageSave_Click(object sender, RoutedEventArgs e)
  266. {
  267. if (imgViewer.Source != null)
  268. {
  269. ExportImage(imgViewer);
  270. }
  271. }
  272. private void ExportImage(Image imageControl)
  273. {
  274. if (imageControl.Source is BitmapImage bitmapImage)
  275. {
  276. try
  277. {
  278. // 1. 获取原始文件路径
  279. string sourcePath = bitmapImage.UriSource.LocalPath;
  280. if (string.IsNullOrEmpty(sourcePath) || !File.Exists(sourcePath))
  281. {
  282. MessageBox.Show("无法确定原始文件路径或文件不存在。");
  283. return;
  284. }
  285. // 2. 弹出保存对话框
  286. VistaSaveFileDialog saveFileDialog = new VistaSaveFileDialog
  287. {
  288. FileName = System.IO.Path.GetFileName(sourcePath), // 默认文件名
  289. DefaultExt = System.IO.Path.GetExtension(sourcePath),
  290. Filter = $"Image Files (*{System.IO.Path.GetExtension(sourcePath)})|*{System.IO.Path.GetExtension(sourcePath)}|All Files (*.*)|*.*"
  291. };
  292. if (saveFileDialog.ShowDialog() == true)
  293. {
  294. // 3. 直接复制文件
  295. File.Copy(sourcePath, saveFileDialog.FileName, true);
  296. // MessageBox.Show("图片导出成功。");
  297. }
  298. }
  299. catch (Exception ex)
  300. {
  301. MessageBox.Show($"导出失败: {ex.Message}");
  302. }
  303. }
  304. else
  305. {
  306. MessageBox.Show("Image控件中没有有效的图像。");
  307. }
  308. }
  309. }
  310. }