├── .gitattributes
├── .gitignore
├── ImageViewer
├── App.xaml
├── App.xaml.cs
├── AssemblyInfo.cs
├── ConsoleExtensions.cs
├── ImageViewer.csproj
├── ImageViewerControl
│ ├── ControlPanel.xaml
│ ├── ControlPanel.xaml.cs
│ ├── Extensions
│ │ ├── BitmapImageExtensions.cs
│ │ ├── ControlExtensions.cs
│ │ └── RectExtensions.cs
│ ├── ImageViewer.cs
│ ├── InCanvas.cs
│ ├── OutCanvas.cs
│ ├── RoiControls
│ │ ├── Adorner
│ │ │ ├── RectangleRoiControlAdorner.cs
│ │ │ └── RoiControlAdorner.cs
│ │ ├── Extensions
│ │ │ └── RoiControlExtensions.cs
│ │ ├── ImageNotLoadedException.cs
│ │ ├── RectangleRoiControl.cs
│ │ ├── RoiControl.cs
│ │ └── ShapeType.cs
│ └── RoiShapes
│ │ ├── RectangleRoiShape.cs
│ │ ├── RoiPoint.cs
│ │ └── RoiShape.cs
├── MainWindow.xaml
└── MainWindow.xaml.cs
├── ImageViewerDemo.DotSettings
├── ImageViewerDemo.sln
├── ImageViewerDemo
├── App.xaml
├── App.xaml.cs
├── AssemblyInfo.cs
├── ConsoleExtensions.cs
├── FodyWeavers.xml
├── FodyWeavers.xsd
├── ImageViewerDemo.csproj
├── MainWindow.xaml
├── MainWindow.xaml.cs
├── PathExtensions.cs
└── UIElementExtensions.cs
├── ReadMe.md
└── RenderTransformImageViewerDemo
├── App.xaml
├── App.xaml.cs
├── AssemblyInfo.cs
├── DebugExtensions.cs
├── MainWindow.xaml
├── MainWindow.xaml.cs
└── RenderTransformImageViewerDemo.csproj
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Build results
17 | [Dd]ebug/
18 | [Dd]ebugPublic/
19 | [Rr]elease/
20 | [Rr]eleases/
21 | x64/
22 | x86/
23 | [Aa][Rr][Mm]/
24 | [Aa][Rr][Mm]64/
25 | bld/
26 | [Bb]in/
27 | [Oo]bj/
28 | [Ll]og/
29 |
30 | # Visual Studio 2015/2017 cache/options directory
31 | .vs/
32 | # Uncomment if you have tasks that create the project's static files in wwwroot
33 | #wwwroot/
34 |
35 | # Visual Studio 2017 auto generated files
36 | Generated\ Files/
37 |
38 | # MSTest test Results
39 | [Tt]est[Rr]esult*/
40 | [Bb]uild[Ll]og.*
41 |
42 | # NUNIT
43 | *.VisualState.xml
44 | TestResult.xml
45 |
46 | # Build Results of an ATL Project
47 | [Dd]ebugPS/
48 | [Rr]eleasePS/
49 | dlldata.c
50 |
51 | # Benchmark Results
52 | BenchmarkDotNet.Artifacts/
53 |
54 | # .NET Core
55 | project.lock.json
56 | project.fragment.lock.json
57 | artifacts/
58 |
59 | # StyleCop
60 | StyleCopReport.xml
61 |
62 | # Files built by Visual Studio
63 | *_i.c
64 | *_p.c
65 | *_h.h
66 | *.ilk
67 | *.meta
68 | *.obj
69 | *.iobj
70 | *.pch
71 | *.pdb
72 | *.ipdb
73 | *.pgc
74 | *.pgd
75 | *.rsp
76 | *.sbr
77 | *.tlb
78 | *.tli
79 | *.tlh
80 | *.tmp
81 | *.tmp_proj
82 | *_wpftmp.csproj
83 | *.log
84 | *.vspscc
85 | *.vssscc
86 | .builds
87 | *.pidb
88 | *.svclog
89 | *.scc
90 |
91 | # Chutzpah Test files
92 | _Chutzpah*
93 |
94 | # Visual C++ cache files
95 | ipch/
96 | *.aps
97 | *.ncb
98 | *.opendb
99 | *.opensdf
100 | *.sdf
101 | *.cachefile
102 | *.VC.db
103 | *.VC.VC.opendb
104 |
105 | # Visual Studio profiler
106 | *.psess
107 | *.vsp
108 | *.vspx
109 | *.sap
110 |
111 | # Visual Studio Trace Files
112 | *.e2e
113 |
114 | # TFS 2012 Local Workspace
115 | $tf/
116 |
117 | # Guidance Automation Toolkit
118 | *.gpState
119 |
120 | # ReSharper is a .NET coding add-in
121 | _ReSharper*/
122 | *.[Rr]e[Ss]harper
123 | *.DotSettings.user
124 |
125 | # JustCode is a .NET coding add-in
126 | .JustCode
127 |
128 | # TeamCity is a build add-in
129 | _TeamCity*
130 |
131 | # DotCover is a Code Coverage Tool
132 | *.dotCover
133 |
134 | # AxoCover is a Code Coverage Tool
135 | .axoCover/*
136 | !.axoCover/settings.json
137 |
138 | # Visual Studio code coverage results
139 | *.coverage
140 | *.coveragexml
141 |
142 | # NCrunch
143 | _NCrunch_*
144 | .*crunch*.local.xml
145 | nCrunchTemp_*
146 |
147 | # MightyMoose
148 | *.mm.*
149 | AutoTest.Net/
150 |
151 | # Web workbench (sass)
152 | .sass-cache/
153 |
154 | # Installshield output folder
155 | [Ee]xpress/
156 |
157 | # DocProject is a documentation generator add-in
158 | DocProject/buildhelp/
159 | DocProject/Help/*.HxT
160 | DocProject/Help/*.HxC
161 | DocProject/Help/*.hhc
162 | DocProject/Help/*.hhk
163 | DocProject/Help/*.hhp
164 | DocProject/Help/Html2
165 | DocProject/Help/html
166 |
167 | # Click-Once directory
168 | publish/
169 |
170 | # Publish Web Output
171 | *.[Pp]ublish.xml
172 | *.azurePubxml
173 | # Note: Comment the next line if you want to checkin your web deploy settings,
174 | # but database connection strings (with potential passwords) will be unencrypted
175 | *.pubxml
176 | *.publishproj
177 |
178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
179 | # checkin your Azure Web App publish settings, but sensitive information contained
180 | # in these scripts will be unencrypted
181 | PublishScripts/
182 |
183 | # NuGet Packages
184 | *.nupkg
185 | # The packages folder can be ignored because of Package Restore
186 | **/[Pp]ackages/*
187 | # except build/, which is used as an MSBuild target.
188 | !**/[Pp]ackages/build/
189 | # Uncomment if necessary however generally it will be regenerated when needed
190 | #!**/[Pp]ackages/repositories.config
191 | # NuGet v3's project.json files produces more ignorable files
192 | *.nuget.props
193 | *.nuget.targets
194 |
195 | # Microsoft Azure Build Output
196 | csx/
197 | *.build.csdef
198 |
199 | # Microsoft Azure Emulator
200 | ecf/
201 | rcf/
202 |
203 | # Windows Store app package directories and files
204 | AppPackages/
205 | BundleArtifacts/
206 | Package.StoreAssociation.xml
207 | _pkginfo.txt
208 | *.appx
209 |
210 | # Visual Studio cache files
211 | # files ending in .cache can be ignored
212 | *.[Cc]ache
213 | # but keep track of directories ending in .cache
214 | !?*.[Cc]ache/
215 |
216 | # Others
217 | ClientBin/
218 | ~$*
219 | *~
220 | *.dbmdl
221 | *.dbproj.schemaview
222 | *.jfm
223 | *.pfx
224 | *.publishsettings
225 | orleans.codegen.cs
226 |
227 | # Including strong name files can present a security risk
228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
229 | #*.snk
230 |
231 | # Since there are multiple workflows, uncomment next line to ignore bower_components
232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
233 | #bower_components/
234 |
235 | # RIA/Silverlight projects
236 | Generated_Code/
237 |
238 | # Backup & report files from converting an old project file
239 | # to a newer Visual Studio version. Backup files are not needed,
240 | # because we have git ;-)
241 | _UpgradeReport_Files/
242 | Backup*/
243 | UpgradeLog*.XML
244 | UpgradeLog*.htm
245 | ServiceFabricBackup/
246 | *.rptproj.bak
247 |
248 | # SQL Server files
249 | *.mdf
250 | *.ldf
251 | *.ndf
252 |
253 | # Business Intelligence projects
254 | *.rdl.data
255 | *.bim.layout
256 | *.bim_*.settings
257 | *.rptproj.rsuser
258 | *- Backup*.rdl
259 |
260 | # Microsoft Fakes
261 | FakesAssemblies/
262 |
263 | # GhostDoc plugin setting file
264 | *.GhostDoc.xml
265 |
266 | # Node.js Tools for Visual Studio
267 | .ntvs_analysis.dat
268 | node_modules/
269 |
270 | # Visual Studio 6 build log
271 | *.plg
272 |
273 | # Visual Studio 6 workspace options file
274 | *.opt
275 |
276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
277 | *.vbw
278 |
279 | # Visual Studio LightSwitch build output
280 | **/*.HTMLClient/GeneratedArtifacts
281 | **/*.DesktopClient/GeneratedArtifacts
282 | **/*.DesktopClient/ModelManifest.xml
283 | **/*.Server/GeneratedArtifacts
284 | **/*.Server/ModelManifest.xml
285 | _Pvt_Extensions
286 |
287 | # Paket dependency manager
288 | .paket/paket.exe
289 | paket-files/
290 |
291 | # FAKE - F# Make
292 | .fake/
293 |
294 | # JetBrains Rider
295 | .idea/
296 | *.sln.iml
297 |
298 | # CodeRush personal settings
299 | .cr/personal
300 |
301 | # Python Tools for Visual Studio (PTVS)
302 | __pycache__/
303 | *.pyc
304 |
305 | # Cake - Uncomment if you are using it
306 | # tools/**
307 | # !tools/packages.config
308 |
309 | # Tabs Studio
310 | *.tss
311 |
312 | # Telerik's JustMock configuration file
313 | *.jmconfig
314 |
315 | # BizTalk build output
316 | *.btp.cs
317 | *.btm.cs
318 | *.odx.cs
319 | *.xsd.cs
320 |
321 | # OpenCover UI analysis results
322 | OpenCover/
323 |
324 | # Azure Stream Analytics local run output
325 | ASALocalRun/
326 |
327 | # MSBuild Binary and Structured Log
328 | *.binlog
329 |
330 | # NVidia Nsight GPU debugger configuration file
331 | *.nvuser
332 |
333 | # MFractors (Xamarin productivity tool) working folder
334 | .mfractor/
335 |
336 | # Local History for Visual Studio
337 | .localhistory/
338 |
339 | # BeatPulse healthcheck temp database
340 | healthchecksdb
--------------------------------------------------------------------------------
/ImageViewer/App.xaml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
--------------------------------------------------------------------------------
/ImageViewer/App.xaml.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 |
3 | namespace ImageViewer
4 | {
5 | ///
6 | /// Interaction logic for App.xaml
7 | ///
8 | public partial class App : Application
9 | {
10 | }
11 | }
--------------------------------------------------------------------------------
/ImageViewer/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 |
3 | [assembly: ThemeInfo(
4 | ResourceDictionaryLocation
5 | .None, //where theme specific resource dictionaries are located
6 | //(used if a resource is not found in the page,
7 | // or application resource dictionaries)
8 | ResourceDictionaryLocation
9 | .SourceAssembly //where the generic resource dictionary is located
10 | //(used if a resource is not found in the page,
11 | // app, or any theme specific resource dictionaries)
12 | )]
--------------------------------------------------------------------------------
/ImageViewer/ConsoleExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace ImageViewer
4 | {
5 | public static class ConsoleExtensions
6 | {
7 | public static void ConsoleSplitLine(char splitLineChar = '_',
8 | ConsoleColor foregroundColor = ConsoleColor.Gray,
9 | ConsoleColor backgroundColor = ConsoleColor.Black)
10 | {
11 | int width = Console.WindowWidth;
12 | new string(splitLineChar, width - 1).WriteLine(foregroundColor,
13 | backgroundColor);
14 | }
15 | public static void WriteLine(this T t,
16 | ConsoleColor foregroundColor = ConsoleColor.Gray,
17 | ConsoleColor backgroundColor = ConsoleColor.Black)
18 | {
19 | ConsoleColor backgroundBuff = Console.BackgroundColor;
20 | ConsoleColor foregroundBuff = Console.ForegroundColor;
21 | Console.BackgroundColor = backgroundColor;
22 | Console.ForegroundColor = foregroundColor;
23 | Console.WriteLine(t);
24 | Console.BackgroundColor = backgroundBuff;
25 | Console.ForegroundColor = foregroundBuff;
26 | }
27 | }
28 | }
--------------------------------------------------------------------------------
/ImageViewer/ImageViewer.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net5.0
6 | true
7 |
8 |
9 |
--------------------------------------------------------------------------------
/ImageViewer/ImageViewerControl/ControlPanel.xaml:
--------------------------------------------------------------------------------
1 |
11 |
12 |
13 |
17 |
18 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
--------------------------------------------------------------------------------
/ImageViewer/ImageViewerControl/ControlPanel.xaml.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics.CodeAnalysis;
2 | using System.Linq;
3 | using System.Windows;
4 | using System.Windows.Controls;
5 | using System.Windows.Controls.Primitives;
6 |
7 | namespace ImageViewer.ImageViewerControl
8 | {
9 | ///
10 | /// ControlPanel.xaml 的交互逻辑
11 | ///
12 | internal partial class ControlPanel : UserControl
13 | {
14 | public ControlPanel(ImageViewer imageViewer)
15 | {
16 | InitializeComponent();
17 | DataContext = imageViewer;
18 | }
19 |
20 | [System.Diagnostics.CodeAnalysis.SuppressMessage("Style",
21 | "RCS1001:Add braces (when expression spans over multiple lines).",
22 | Justification = "<挂起>")]
23 | [SuppressMessage("ReSharper", "PossibleNullReferenceException")]
24 | private void ToggleButtons_OnChecked(object sender, RoutedEventArgs e)
25 | {
26 | var toggleButton = sender as ToggleButton;
27 | var wrapPanel = toggleButton.Parent as WrapPanel;
28 | foreach (ToggleButton button in wrapPanel.Children.OfType())
29 | if (button != toggleButton)
30 | button.IsChecked = false;
31 | }
32 | }
33 | }
--------------------------------------------------------------------------------
/ImageViewer/ImageViewerControl/Extensions/BitmapImageExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics.CodeAnalysis;
2 | using System.Windows.Media.Imaging;
3 |
4 | namespace ImageViewer.ImageViewerControl.Extensions
5 | {
6 | internal static class BitmapImageExtensions
7 | {
8 | public static (double width, double height) GetWH(this BitmapImage bitmapImage)
9 | {
10 | double width = bitmapImage.Width;
11 | double height = bitmapImage.Height;
12 | return (width, height);
13 | }
14 | }
15 | }
--------------------------------------------------------------------------------
/ImageViewer/ImageViewerControl/Extensions/ControlExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics.CodeAnalysis;
2 | using System.Windows;
3 | using System.Windows.Controls;
4 |
5 | namespace ImageViewer.ImageViewerControl.Extensions
6 | {
7 | internal static class ControlExtensions
8 | {
9 | public static (double x, double y) GetCanvasXY(this UIElement frameworkElement)
10 | {
11 | double x = Canvas.GetLeft(frameworkElement);
12 | double y = Canvas.GetTop(frameworkElement);
13 | x = double.IsNaN(x) ? 0 : x;
14 | y = double.IsNaN(y) ? 0 : y;
15 | return (x, y);
16 | }
17 |
18 | public static (double width, double height) GetWH(
19 | this FrameworkElement frameworkElement)
20 | {
21 | double width = frameworkElement.Width;
22 | double height = frameworkElement.Height;
23 | return (width, height);
24 | }
25 |
26 | public static void SetCanvasXY(this UIElement frameworkElement,
27 | double left,
28 | double top)
29 | {
30 | Canvas.SetLeft(frameworkElement, left);
31 | Canvas.SetTop(frameworkElement, top);
32 | }
33 |
34 | public static void SetWH(this FrameworkElement frameworkElement,
35 | double width,
36 | double height)
37 | {
38 | frameworkElement.Width = width;
39 | frameworkElement.Height = height;
40 | }
41 | }
42 | }
--------------------------------------------------------------------------------
/ImageViewer/ImageViewerControl/Extensions/RectExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 | using System.Windows.Media;
3 | using System.Windows.Shapes;
4 |
5 | namespace ImageViewer.ImageViewerControl.Extensions
6 | {
7 | internal static class PathExtensions
8 | {
9 | public static void SetRoiPathFill(this Path path)
10 | {
11 | path.Fill = new SolidColorBrush(Color.FromArgb(1, 0, 0, 0));
12 | }
13 |
14 | public static void SetRoiPathNullFill(this Path path)
15 | {
16 | path.Fill = default;
17 | }
18 | }
19 |
20 | internal static class RectExtensions
21 | {
22 | public static (double x, double y, double width, double height)
23 | GetPositionAndSize(this Rect rect)
24 | {
25 | return (rect.X, rect.Y, rect.Width, rect.Height);
26 | }
27 | }
28 | }
--------------------------------------------------------------------------------
/ImageViewer/ImageViewerControl/ImageViewer.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Immutable;
3 | using System.Diagnostics.CodeAnalysis;
4 | using System.Linq;
5 | using System.Windows;
6 | using System.Windows.Controls;
7 | using System.Windows.Media;
8 | using System.Windows.Media.Imaging;
9 | using ImageViewer.ImageViewerControl.Extensions;
10 | using ImageViewer.ImageViewerControl.RoiControls;
11 |
12 | namespace ImageViewer.ImageViewerControl
13 | {
14 | public class ImageViewer : ContentControl
15 | {
16 | public static readonly DependencyProperty IsImageLoadedProperty;
17 |
18 | ///
19 | /// 是否修改ROI
20 | ///
21 | public static readonly DependencyProperty IsModifyRoiProperty =
22 | DependencyProperty.Register(nameof(IsModifyRoi),
23 | typeof(bool),
24 | typeof(ImageViewer),
25 | new PropertyMetadata(default(bool),
26 | IsModifyRoiPropertyChangedCallback));
27 |
28 | ///
29 | /// 是否移动与缩放ROI
30 | ///
31 | public static readonly DependencyProperty IsMoveAndScaleProperty =
32 | DependencyProperty.Register(nameof(IsMoveAndScale),
33 | typeof(bool),
34 | typeof(ImageViewer),
35 | new PropertyMetadata(default(bool)));
36 |
37 | ///
38 | /// 是否画矩形ROI
39 | ///
40 | public static readonly DependencyProperty IsRectangleProperty =
41 | DependencyProperty.Register(nameof(IsRectangle),
42 | typeof(bool),
43 | typeof(ImageViewer),
44 | new PropertyMetadata(default(bool)));
45 |
46 | ///
47 | /// 是否画旋转矩形ROI
48 | ///
49 | public static readonly DependencyProperty IsRotateRectangleProperty =
50 | DependencyProperty.Register(nameof(IsRotateRectangle),
51 | typeof(bool),
52 | typeof(ImageViewer),
53 | new PropertyMetadata(default(bool)));
54 |
55 | ///
56 | /// 最大缩放倍数
57 | ///
58 | public static readonly DependencyProperty MaxScaleProperty =
59 | DependencyProperty.Register(nameof(MaxScale),
60 | typeof(double),
61 | typeof(ImageViewer),
62 | new PropertyMetadata((double) 10));
63 |
64 | ///
65 | /// 最小缩放倍数
66 | ///
67 | public static readonly DependencyProperty MinScaleProperty =
68 | DependencyProperty.Register(nameof(MinScale),
69 | typeof(double),
70 | typeof(ImageViewer),
71 | new PropertyMetadata(0.00000000001));
72 |
73 | ///
74 | /// 缩放系数,一次缩放多少倍
75 | ///
76 | public static readonly DependencyProperty ScaleFactorProperty =
77 | DependencyProperty.Register(nameof(ScaleFactor),
78 | typeof(double),
79 | typeof(ImageViewer),
80 | new PropertyMetadata(0.05));
81 |
82 | public static readonly DependencyProperty SelectInsideOrOutlineProperty =
83 | DependencyProperty.Register(nameof(SelectInsideOrOutline),
84 | typeof(bool),
85 | typeof(ImageViewer),
86 | new PropertyMetadata(default(bool),
87 | SelectOutlineOrInsidePropertyChangedCallback));
88 |
89 | ///
90 | /// 缩放倍数
91 | ///
92 | internal static readonly DependencyProperty ScaleProperty =
93 | DependencyProperty.Register(nameof(Scale),
94 | typeof(double),
95 | typeof(ImageViewer),
96 | new PropertyMetadata((double) 1));
97 |
98 | ///
99 | /// 图片是否已经加载
100 | ///
101 | private static readonly DependencyPropertyKey IsImageLoadedPropertyKey =
102 | DependencyProperty.RegisterReadOnly(nameof(IsImageLoaded),
103 | typeof(bool),
104 | typeof(ImageViewer),
105 | new PropertyMetadata(default(bool)));
106 |
107 | internal Image Image;
108 | internal InCanvas InCanvas;
109 | internal OutCanvas OutCanvas;
110 |
111 | static ImageViewer()
112 | {
113 | IsImageLoadedProperty = IsImageLoadedPropertyKey.DependencyProperty;
114 | }
115 |
116 | public bool IsImageLoaded => (bool) GetValue(IsImageLoadedProperty);
117 |
118 | public bool IsModifyRoi
119 | {
120 | get => (bool) GetValue(IsModifyRoiProperty);
121 | set => SetValue(IsModifyRoiProperty, value);
122 | }
123 |
124 | public bool IsMoveAndScale
125 | {
126 | get => (bool) GetValue(IsMoveAndScaleProperty);
127 | set => SetValue(IsMoveAndScaleProperty, value);
128 | }
129 |
130 | public bool IsRectangle
131 | {
132 | get => (bool) GetValue(IsRectangleProperty);
133 | set => SetValue(IsRectangleProperty, value);
134 | }
135 |
136 | public bool IsRotateRectangle
137 | {
138 | get => (bool) GetValue(IsRotateRectangleProperty);
139 | set => SetValue(IsRotateRectangleProperty, value);
140 | }
141 |
142 | public double MaxScale
143 | {
144 | get => (double) GetValue(MaxScaleProperty);
145 | set => SetValue(MaxScaleProperty, value);
146 | }
147 |
148 | public double MinScale
149 | {
150 | get => (double) GetValue(MinScaleProperty);
151 | set => SetValue(MinScaleProperty, value);
152 | }
153 |
154 | public double Scale
155 | {
156 | get => (double) GetValue(ScaleProperty);
157 | internal set => SetValue(ScaleProperty, value);
158 | }
159 |
160 | ///
161 | /// 缩放系数
162 | ///
163 | public double ScaleFactor
164 | {
165 | get => (double) GetValue(ScaleFactorProperty);
166 | set => SetValue(ScaleFactorProperty, value);
167 | }
168 |
169 | ///
170 | /// 当需要修改ROI时,点击ROI的轮廓还是内部可以选中ROI
171 | ///
172 | ///
173 | /// true为点击ROI内部选中ROI,false为点击ROI轮廓选中ROI
174 | ///
175 | public bool SelectInsideOrOutline
176 | {
177 | get => (bool) GetValue(SelectInsideOrOutlineProperty);
178 | set => SetValue(SelectInsideOrOutlineProperty, value);
179 | }
180 |
181 | private bool IsImageLoadedKey
182 | {
183 | get => (bool) GetValue(IsImageLoadedPropertyKey.DependencyProperty);
184 | set => SetValue(IsImageLoadedPropertyKey, value);
185 | }
186 |
187 | public void AddRoi(RoiControl roi)
188 | {
189 | roi.ImageViewer = this;
190 | InCanvas.Children.Add(roi);
191 | }
192 |
193 | public void ClearRoi()
194 | {
195 | foreach (RoiControl roiShape in GetRoi())
196 | InCanvas.Children.Remove(roiShape);
197 | }
198 |
199 | ///
200 | /// 获取控件内部的两个Canvas的RenderSize
201 | ///
202 | ///
203 | public (Size outCanvasRenderSize, Size inCanvasRenderSize)
204 | GetCanvasesRenderSize()
205 | {
206 | Size outCanvasRenderSize = OutCanvas.RenderSize;
207 | Size inCanvasRenderSize = InCanvas.RenderSize;
208 | return (outCanvasRenderSize, inCanvasRenderSize);
209 | }
210 |
211 | public ImmutableArray GetRoi()
212 | {
213 | return InCanvas.Children.OfType().ToImmutableArray();
214 | }
215 |
216 | public (double scale, double scaleFactor, double minScale, double maxScale)
217 | GetScaleInfo()
218 | {
219 | return (Scale, ScaleFactor, MinScale, MaxScale);
220 | }
221 |
222 | ///
223 | /// 在控件中显示图片
224 | ///
225 | /// 图片路径
226 | public void LoadImage(string filePath)
227 | {
228 | var bitmapImage = new BitmapImage(new Uri(filePath));
229 | SetInsideControlsInfo_When_LoadImage(bitmapImage);
230 | IsImageLoadedKey = true;
231 | ClearRoi();
232 | }
233 |
234 | public void RemoveLastRoi()
235 | {
236 | ImmutableArray _roiShapes = GetRoi();
237 | if (_roiShapes.Length != 0)
238 | InCanvas.Children.Remove(_roiShapes.Last());
239 | }
240 |
241 | protected override void OnInitialized(EventArgs e)
242 | {
243 | base.OnInitialized(e);
244 | Initialization_Layout_ChildrenControl();
245 | }
246 |
247 | private static void IsModifyRoiPropertyChangedCallback(DependencyObject d,
248 | DependencyPropertyChangedEventArgs e)
249 | {
250 | var imageViewer = (ImageViewer) d;
251 | if (imageViewer.IsModifyRoi == false)
252 | foreach (RoiControl roiControl in imageViewer.GetRoi())
253 | roiControl.IsSelected = false;
254 | }
255 |
256 | private static void SelectOutlineOrInsidePropertyChangedCallback(
257 | DependencyObject d,
258 | DependencyPropertyChangedEventArgs e)
259 | {
260 | var viewer = (ImageViewer) d;
261 | ImmutableList controls = viewer.GetRoi()
262 | .Where(control => control.ContentPath != null)
263 | .ToImmutableList();
264 | viewer.SelectInsideOrOutline.WriteLine();
265 | if (viewer.SelectInsideOrOutline)
266 | controls.ForEach(control => control.ContentPath.SetRoiPathNullFill());
267 | else
268 | controls.ForEach(control => control.ContentPath.SetRoiPathFill());
269 | }
270 |
271 | ///
272 | /// 初始化并布局子空间
273 | ///
274 | /// 初始化此控件。 此控件的结构为: Gird分为两行,第一行存放着_outCanvas,第二行存放着该控件的一些功能选择按钮,例如是否缩放、移动图片等等。
275 | /// _outCanvas包含着_inCanvas。
276 | /// _inCanvas包含着_image。
277 | ///
278 | ///
279 | private void Initialization_Layout_ChildrenControl()
280 | {
281 | var grid = new Grid
282 | {
283 | RowDefinitions =
284 | {
285 | new RowDefinition(),
286 | new RowDefinition {Height = GridLength.Auto}
287 | }
288 | };
289 | Content = grid;
290 | InCanvas = new InCanvas(this) {Background = Brushes.Green};
291 | OutCanvas = new OutCanvas(this)
292 | {
293 | Background = Brushes.Black, ClipToBounds = true
294 | };
295 | grid.Children.Add(OutCanvas);
296 | OutCanvas.Children.Add(InCanvas);
297 | var controlPanel = new ControlPanel(this);
298 | grid.Children.Add(controlPanel);
299 | Grid.SetRow(controlPanel, 1);
300 | }
301 |
302 | ///
303 | /// 当加载图片时设置内部控件的属性。
304 | ///
305 | ///
306 | /// _image的长宽与其Canvas.Left、Canvas.Top。
307 | /// _inCanvas的长宽与其Canvas.Left、Canvas.Top。
308 | ///
309 | ///
310 | [SuppressMessage("Readability",
311 | "RCS1123:Add parentheses when necessary.",
312 | Justification = "<挂起>")]
313 | private void SetInsideControlsInfo_When_LoadImage(BitmapImage bitmapImage)
314 | {
315 | Scale = 1;
316 | if (Image == null)
317 | {
318 | Image = new Image {Source = bitmapImage};
319 | InCanvas.Children.Add(Image);
320 | }
321 | else
322 | {
323 | Image.Source = bitmapImage;
324 | }
325 |
326 | (double width, double height) = bitmapImage.GetWH();
327 | Image.SetWH(width, height);
328 | InCanvas.RenderTransform = new ScaleTransform(1, 1);
329 | (double inW, double inH) = (width * 100, height * 100);
330 | InCanvas.SetWH(inW, inH);
331 | (double x, double y) = (inW / 2 - width / 2, inH / 2 - height / 2);
332 | Image.SetCanvasXY(x, y);
333 | InCanvas.SetCanvasXY(-x, -y);
334 | }
335 | }
336 | }
--------------------------------------------------------------------------------
/ImageViewer/ImageViewerControl/InCanvas.cs:
--------------------------------------------------------------------------------
1 | using ImageViewer.ImageViewerControl.Extensions;
2 | using System.Linq;
3 | using System.Windows;
4 | using System.Windows.Controls;
5 | using System.Windows.Input;
6 | using ImageViewer.ImageViewerControl.RoiControls;
7 | namespace ImageViewer.ImageViewerControl
8 | {
9 | internal class InCanvas : Canvas
10 | {
11 | private readonly ImageViewer _imageViewer;
12 | private Point _buffPoint;
13 | private RoiControl _buffRoiControl;
14 | public InCanvas(ImageViewer imageViewer)
15 | {
16 | _imageViewer = imageViewer;
17 | }
18 | protected override void OnMouseDown(MouseButtonEventArgs e)
19 | {
20 | base.OnMouseDown(e);
21 | if (IsRectangleConditionOk(e))
22 | {
23 | _buffPoint = e.GetPosition(this);
24 | _buffRoiControl = default;
25 | }
26 | }
27 | protected override void OnMouseMove(MouseEventArgs e)
28 | {
29 | base.OnMouseMove(e);
30 | if (IsRectangleConditionOk(e))
31 | {
32 | Point position = e.GetPosition(this);
33 | Vector vector = position - _buffPoint;
34 | var rect = new Rect(_buffPoint, vector);
35 | (double x, double y, double width, double height) =
36 | rect.GetPositionAndSize();
37 | if (_buffRoiControl == null)
38 | {
39 | _buffRoiControl = new RectangleRoiControl(x, y, width, height);
40 | _imageViewer.AddRoi(_buffRoiControl);
41 | }
42 | RectangleRoiControl rectangleRoiControl = Children
43 | .OfType()
44 | .Single(roi => roi == _buffRoiControl);
45 | rectangleRoiControl.SetPositionAndSize(x, y, width, height);
46 | }
47 | }
48 | private bool IsRectangleConditionOk(MouseEventArgs e)
49 | {
50 | return _imageViewer.IsRectangle &&
51 | (e.LeftButton == MouseButtonState.Pressed ||
52 | e.RightButton == MouseButtonState.Pressed);
53 | }
54 | private bool IsRectangleConditionOk(MouseButtonEventArgs e)
55 | {
56 | return _imageViewer.IsRectangle &&
57 | (e.LeftButton == MouseButtonState.Pressed ||
58 | e.RightButton == MouseButtonState.Pressed);
59 | }
60 | }
61 | }
--------------------------------------------------------------------------------
/ImageViewer/ImageViewerControl/OutCanvas.cs:
--------------------------------------------------------------------------------
1 | using ImageViewer.ImageViewerControl.Extensions;
2 | using System;
3 | using System.Windows;
4 | using System.Windows.Controls;
5 | using System.Windows.Input;
6 | using System.Windows.Media;
7 |
8 | namespace ImageViewer.ImageViewerControl
9 | {
10 | internal class OutCanvas : Canvas
11 | {
12 | private readonly ImageViewer _imageViewer;
13 | private readonly InCanvas _inCanvas;
14 | private Point _buffPoint;
15 |
16 | protected override void OnMouseDown(MouseButtonEventArgs e)
17 | {
18 | if (IsMoveAndScaleConditionOk(e))
19 | _buffPoint = e.GetPosition(this);
20 | base.OnMouseDown(e);
21 | }
22 |
23 | protected override void OnMouseMove(MouseEventArgs e)
24 | {
25 | if (IsMoveAndScaleConditionOk(e))
26 | {
27 | Point position = e.GetPosition(this);
28 | Vector vector = position - _buffPoint;
29 | (double x, double y) = _inCanvas.GetCanvasXY();
30 | (double newX, double newY) = (x + vector.X, y + vector.Y);
31 | _inCanvas.SetCanvasXY(newX, newY);
32 | _buffPoint = position;
33 | }
34 |
35 | base.OnMouseMove(e);
36 | }
37 |
38 | [System.Diagnostics.CodeAnalysis.SuppressMessage("Readability",
39 | "RCS1123:Add parentheses when necessary.",
40 | Justification = "<挂起>")]
41 | protected override void OnMouseWheel(MouseWheelEventArgs e)
42 | {
43 | if (_imageViewer.IsMoveAndScale)
44 | {
45 | (double scale, double scaleFactor, double minScale, double maxScale) =
46 | _imageViewer.GetScaleInfo();
47 | int i = e.Delta > 0 ? 1 : -1;
48 | double d = scale + scaleFactor * i;
49 | if (d > minScale && d < maxScale)
50 | {
51 | _imageViewer.Scale = d;
52 | _inCanvas.RenderTransformOrigin = new Point(0.5, 0.5);
53 | _inCanvas.RenderTransform = new ScaleTransform(d, d);
54 | }
55 | }
56 |
57 | base.OnMouseWheel(e);
58 | }
59 |
60 | private bool IsMoveAndScaleConditionOk(MouseButtonEventArgs e)
61 | {
62 | return _imageViewer.IsMoveAndScale &&
63 | (e.LeftButton == MouseButtonState.Pressed ||
64 | e.RightButton == MouseButtonState.Pressed);
65 | }
66 |
67 | private bool IsMoveAndScaleConditionOk(MouseEventArgs e)
68 | {
69 | return _imageViewer.IsMoveAndScale &&
70 | (e.LeftButton == MouseButtonState.Pressed ||
71 | e.RightButton == MouseButtonState.Pressed);
72 | }
73 |
74 | public OutCanvas(ImageViewer imageViewer)
75 | {
76 | _imageViewer = imageViewer ??
77 | throw new ArgumentNullException(nameof(imageViewer));
78 | _inCanvas = imageViewer.InCanvas;
79 | }
80 | }
81 | }
--------------------------------------------------------------------------------
/ImageViewer/ImageViewerControl/RoiControls/Adorner/RectangleRoiControlAdorner.cs:
--------------------------------------------------------------------------------
1 | using System.Windows.Controls.Primitives;
2 | using System.Windows.Media;
3 |
4 | namespace ImageViewer.ImageViewerControl.RoiControls.Adorner
5 | {
6 | public class RectangleRoiControlAdorner : RoiControlAdorner
7 | {
8 |
9 | public RectangleRoiControlAdorner(RectangleRoiControl adornedElement) : base(
10 | adornedElement)
11 | {
12 |
13 | }
14 |
15 | protected override void OnRender(DrawingContext drawingContext)
16 | {
17 | base.OnRender(drawingContext);
18 | }
19 | }
20 | }
--------------------------------------------------------------------------------
/ImageViewer/ImageViewerControl/RoiControls/Adorner/RoiControlAdorner.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 | using System.Windows.Controls.Primitives;
3 | using System.Windows.Media;
4 | using ImageViewer.ImageViewerControl.Extensions;
5 |
6 | namespace ImageViewer.ImageViewerControl.RoiControls.Adorner
7 | {
8 | public abstract class RoiControlAdorner : System.Windows.Documents.Adorner
9 | {
10 | public static readonly DependencyPropertyKey ChildrenPropertyKey =
11 | DependencyProperty.RegisterReadOnly(nameof(Children),
12 | typeof(VisualCollection),
13 | typeof(RoiControlAdorner),
14 | new PropertyMetadata(default(VisualCollection)));
15 |
16 | public static readonly DependencyProperty ChildrenProperty =
17 | ChildrenPropertyKey.DependencyProperty;
18 |
19 | public VisualCollection Children => (VisualCollection) GetValue(ChildrenProperty);
20 |
21 | VisualCollection ChildrenKey
22 | {
23 | get => (VisualCollection) GetValue(ChildrenPropertyKey.DependencyProperty);
24 | set => SetValue(ChildrenPropertyKey, value);
25 | }
26 |
27 | protected override Visual GetVisualChild(int index)
28 | {
29 | return Children[index];
30 | }
31 |
32 | protected override int VisualChildrenCount => Children.Count;
33 |
34 | protected virtual Thumb MoveThumb { get; set; } = new Thumb()
35 | {
36 | Background = Brushes.DarkRed, Height = 25, Width = 25,
37 | };
38 |
39 | protected RoiControlAdorner(RoiControl adornedElement) : base(adornedElement)
40 | {
41 | ChildrenKey = new VisualCollection(this);
42 | MoveThumb.DragDelta += OnMoveThumbDragDelta;
43 | Children.Add(MoveThumb);
44 | }
45 |
46 | protected override Size ArrangeOverride(Size finalSize)
47 | {
48 | Size desiredSize = AdornedElement.DesiredSize;
49 | MoveThumb.Arrange(new Rect(desiredSize.Width / 2 - MoveThumb.Width / 2,
50 | desiredSize.Height / 2 - MoveThumb.Height / 2,
51 | MoveThumb.Width,
52 | MoveThumb.Height));
53 | return base.ArrangeOverride(finalSize);
54 | }
55 |
56 | protected override Size MeasureOverride(Size constraint)
57 | {
58 | MoveThumb.Measure(constraint);
59 | return base.MeasureOverride(constraint);
60 | }
61 |
62 | protected virtual void OnMoveThumbDragDelta(object sender, DragDeltaEventArgs e)
63 | {
64 | (double x, double y) = AdornedElement.GetCanvasXY();
65 | double horizontalChange = e.HorizontalChange;
66 | double verticalChange = e.VerticalChange;
67 | (double newX, double newY) = (x + horizontalChange, y + verticalChange);
68 | AdornedElement.SetCanvasXY(newX, newY);
69 | }
70 | }
71 | }
--------------------------------------------------------------------------------
/ImageViewer/ImageViewerControl/RoiControls/Extensions/RoiControlExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.Windows.Documents;
2 |
3 | namespace ImageViewer.ImageViewerControl.RoiControls.Extensions
4 | {
5 | internal static class RoiControlExtensions
6 | {
7 | public static AdornerLayer GetAdornerLayer(this RoiControl roiControl)
8 | {
9 | return AdornerLayer.GetAdornerLayer(roiControl);
10 | }
11 | }
12 | }
--------------------------------------------------------------------------------
/ImageViewer/ImageViewerControl/RoiControls/ImageNotLoadedException.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.Serialization;
3 |
4 | namespace ImageViewer.ImageViewerControl.RoiControls
5 | {
6 | public class ImageNotLoadedException : Exception
7 | {
8 | public ImageNotLoadedException() : base("还未加载任何图片,无法执行此操作!")
9 | {
10 | }
11 |
12 | protected ImageNotLoadedException(SerializationInfo info,
13 | StreamingContext context) : base(info, context)
14 | {
15 | }
16 |
17 | public ImageNotLoadedException(string message) : base(message)
18 | {
19 | }
20 |
21 | public ImageNotLoadedException(string message, Exception innerException) : base(
22 | message,
23 | innerException)
24 | {
25 | }
26 | }
27 | }
--------------------------------------------------------------------------------
/ImageViewer/ImageViewerControl/RoiControls/RectangleRoiControl.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 | using System.Windows.Controls;
3 | using System.Windows.Documents;
4 | using System.Windows.Media;
5 | using System.Windows.Shapes;
6 | using ImageViewer.ImageViewerControl.Extensions;
7 | using ImageViewer.ImageViewerControl.RoiControls.Adorner;
8 | using ImageViewer.ImageViewerControl.RoiControls.Extensions;
9 | using ImageViewer.ImageViewerControl.RoiShapes;
10 |
11 | namespace ImageViewer.ImageViewerControl.RoiControls
12 | {
13 | public class RectangleRoiControl : RoiControl
14 | {
15 | internal RectangleRoiControl(double x, double y, double width, double height) :
16 | base(ShapeType.Rectangle)
17 | {
18 | SetPositionAndSize(x, y, width, height);
19 | }
20 |
21 | public static RectangleRoiControl CreateRoi(double x,
22 | double y,
23 | double width,
24 | double height,
25 | ImageViewer imageViewer)
26 | {
27 | if (imageViewer.IsImageLoaded == false)
28 | {
29 | throw new ImageNotLoadedException();
30 | }
31 |
32 | Image image = imageViewer.Image;
33 | (double dx, double dy) = image.GetCanvasXY();
34 | return new RectangleRoiControl(dx + x, dy + y, width, height);
35 | }
36 |
37 | protected override RoiControlAdorner GetRoiControlAdorner()
38 | {
39 | return new RectangleRoiControlAdorner(this);
40 | }
41 |
42 | ///
43 | /// 获取此Roi相对于图片坐标系的左上角的坐标
44 | ///
45 | ///
46 | public override RoiShape GetRoiShape()
47 | {
48 | Image image = ImageViewer.Image;
49 | Point point = TranslatePoint(new Point(0, 0), image);
50 | return new RectangleRoiShape()
51 | {
52 | Width = Width,
53 | Height = Height,
54 | LeftTopPoint = new RoiPoint(point.X, point.Y)
55 | };
56 | }
57 |
58 | ///
59 | /// 设置此Roi相对于画布坐标系的位置与尺寸
60 | ///
61 | ///
62 | ///
63 | ///
64 | ///
65 | internal void SetPositionAndSize(double x,
66 | double y,
67 | double width,
68 | double height)
69 | {
70 | this.SetWH(width, height);
71 | RenderRectangle(width, height);
72 | this.SetCanvasXY(x, y);
73 | }
74 |
75 | private void RenderRectangle(double width, double height)
76 | {
77 | Content = new Path
78 | {
79 | Data = new RectangleGeometry(new Rect(0, 0, width, height)),
80 | StrokeThickness = 5,
81 | Stroke = Brushes.DarkRed,
82 | };
83 | ContentPath.SetRoiPathFill();
84 | }
85 | }
86 | }
--------------------------------------------------------------------------------
/ImageViewer/ImageViewerControl/RoiControls/RoiControl.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 | using System.Windows.Controls;
3 | using System.Windows.Documents;
4 | using System.Windows.Input;
5 | using System.Windows.Media;
6 | using System.Windows.Shapes;
7 | using ImageViewer.ImageViewerControl.RoiControls.Adorner;
8 | using ImageViewer.ImageViewerControl.RoiControls.Extensions;
9 | using ImageViewer.ImageViewerControl.RoiShapes;
10 |
11 | namespace ImageViewer.ImageViewerControl.RoiControls
12 | {
13 | public abstract class RoiControl : ContentControl
14 | {
15 | public static readonly DependencyProperty TypeProperty =
16 | DependencyProperty.Register(nameof(Type),
17 | typeof(ShapeType),
18 | typeof(RoiControl),
19 | new PropertyMetadata(default(ShapeType)));
20 |
21 | protected internal ImageViewer ImageViewer;
22 |
23 | internal static readonly DependencyProperty IsSelectedProperty =
24 | DependencyProperty.Register(nameof(IsSelected),
25 | typeof(bool),
26 | typeof(RoiControl),
27 | new PropertyMetadata(default(bool), IsSelectedPropertyChangedCallback));
28 |
29 | private static void IsSelectedPropertyChangedCallback(DependencyObject d,
30 | DependencyPropertyChangedEventArgs e)
31 | {
32 | var roiControl = (RoiControl) d;
33 | AdornerLayer layer = roiControl.AdornerLayer;
34 | System.Windows.Documents.Adorner[] adorners = layer.GetAdorners(roiControl);
35 | if (roiControl.IsSelected)
36 | {
37 | foreach (System.Windows.Documents.Adorner adorner in adorners)
38 | {
39 | adorner.Visibility = Visibility.Visible;
40 | }
41 | }
42 | else
43 | {
44 | foreach (System.Windows.Documents.Adorner adorner in adorners)
45 | {
46 | adorner.Visibility = Visibility.Collapsed;
47 | }
48 | }
49 |
50 | roiControl.IsSelected.WriteLine();
51 | }
52 |
53 | protected AdornerLayer AdornerLayer;
54 |
55 | internal bool IsSelected
56 | {
57 | get => (bool) GetValue(IsSelectedProperty);
58 | set => SetValue(IsSelectedProperty, value);
59 | }
60 |
61 | protected RoiControl(ShapeType shapeType)
62 | {
63 | Type = shapeType;
64 | }
65 |
66 | protected abstract RoiControlAdorner GetRoiControlAdorner();
67 |
68 | protected override void OnRender(DrawingContext drawingContext)
69 | {
70 | if (AdornerLayer == null)
71 | {
72 | AdornerLayer layer = this.GetAdornerLayer();
73 | layer.Add(GetRoiControlAdorner());
74 | foreach (System.Windows.Documents.Adorner adorner in layer.GetAdorners(
75 | this))
76 | adorner.Visibility = Visibility.Collapsed;
77 | AdornerLayer = layer;
78 | }
79 |
80 | base.OnRender(drawingContext);
81 | }
82 |
83 | public ShapeType Type
84 | {
85 | get => (ShapeType) GetValue(TypeProperty);
86 | set => SetValue(TypeProperty, value);
87 | }
88 |
89 | public static RectangleRoiControl CreateRectangleRoi(double x,
90 | double y,
91 | double width,
92 | double height,
93 | ImageViewer imageViewer)
94 | {
95 | return RectangleRoiControl.CreateRoi(x, y, width, height, imageViewer);
96 | }
97 |
98 | protected override void OnMouseDown(MouseButtonEventArgs e)
99 | {
100 | if (ImageViewer.IsModifyRoi)
101 | {
102 | foreach (RoiControl roiControl in ImageViewer.GetRoi())
103 | roiControl.IsSelected = false;
104 | IsSelected = true;
105 | }
106 |
107 | base.OnMouseDown(e);
108 | }
109 |
110 | public Path ContentPath => Content as Path;
111 | public abstract RoiShape GetRoiShape();
112 | }
113 | }
--------------------------------------------------------------------------------
/ImageViewer/ImageViewerControl/RoiControls/ShapeType.cs:
--------------------------------------------------------------------------------
1 | namespace ImageViewer.ImageViewerControl.RoiControls
2 | {
3 | public enum ShapeType
4 | {
5 | Rectangle, RotateRectangle
6 | }
7 | }
--------------------------------------------------------------------------------
/ImageViewer/ImageViewerControl/RoiShapes/RectangleRoiShape.cs:
--------------------------------------------------------------------------------
1 | using ImageViewer.ImageViewerControl.RoiControls;
2 |
3 | namespace ImageViewer.ImageViewerControl.RoiShapes
4 | {
5 | public class RectangleRoiShape : RoiShape
6 | {
7 | public RoiPoint LeftTopPoint { get; set; }
8 | public double Width { get; set; }
9 | public double Height { get; set; }
10 |
11 | public RectangleRoiShape() : base(ShapeType.Rectangle)
12 | {
13 | }
14 | }
15 | }
--------------------------------------------------------------------------------
/ImageViewer/ImageViewerControl/RoiShapes/RoiPoint.cs:
--------------------------------------------------------------------------------
1 | namespace ImageViewer.ImageViewerControl.RoiShapes
2 | {
3 | public class RoiPoint
4 | {
5 | public RoiPoint(double x, double y)
6 | {
7 | X = x;
8 | Y = y;
9 | }
10 |
11 | public RoiPoint()
12 | {
13 | }
14 |
15 | public double X { get; set; }
16 | public double Y { get; set; }
17 | }
18 | }
--------------------------------------------------------------------------------
/ImageViewer/ImageViewerControl/RoiShapes/RoiShape.cs:
--------------------------------------------------------------------------------
1 | using ImageViewer.ImageViewerControl.RoiControls;
2 |
3 | namespace ImageViewer.ImageViewerControl.RoiShapes
4 | {
5 | public abstract class RoiShape
6 | {
7 | protected RoiShape(ShapeType shapeType)
8 | {
9 | Type = shapeType;
10 | }
11 |
12 | public ShapeType Type { get; }
13 | }
14 | }
--------------------------------------------------------------------------------
/ImageViewer/MainWindow.xaml:
--------------------------------------------------------------------------------
1 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
25 |
29 |
33 |
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/ImageViewer/MainWindow.xaml.cs:
--------------------------------------------------------------------------------
1 | using System.IO;
2 | using System.Text.Json;
3 | using System.Windows;
4 | using ImageViewer.ImageViewerControl.RoiControls;
5 | using ImageViewer.ImageViewerControl.RoiShapes;
6 |
7 | namespace ImageViewer
8 | {
9 | ///
10 | /// Interaction logic for MainWindow.xaml
11 | ///
12 | public partial class MainWindow : Window
13 | {
14 | private int _index;
15 |
16 | public MainWindow()
17 | {
18 | InitializeComponent();
19 | }
20 |
21 | private void 获取Roi的形状数据Button_OnClick(object sender, RoutedEventArgs e)
22 | {
23 | foreach (RectangleRoiControl rectangleRoi in Viewer.GetRoi()
24 | .OfType())
25 | {
26 | var roiControl = (RoiControl) rectangleRoi;
27 | JsonSerializer.Serialize(roiControl.GetRoiShape() as RectangleRoiShape)
28 | .WriteLine();
29 | }
30 | }
31 |
32 | private void Viewer_OnLoaded(object sender, RoutedEventArgs e)
33 | {
34 | 加载图片Button_OnClick(default, default);
35 | }
36 |
37 | private void 加载图片Button_OnClick(object sender, RoutedEventArgs e)
38 | {
39 | var directoryInfo =
40 | new DirectoryInfo(@"C:\Users\Taurus Zhou\Pictures\Saved Pictures");
41 | FileInfo[] fileInfos = directoryInfo.GetFiles("*.jpg");
42 | FileInfo fileInfo = fileInfos[_index % fileInfos.Length];
43 | Viewer.LoadImage(fileInfo.FullName);
44 | _index++;
45 | }
46 |
47 | private void 添加RoiButton_OnClick(object sender, RoutedEventArgs e)
48 | {
49 | Viewer.AddRoi(RoiControl.CreateRectangleRoi(0, 0, 100, 100, Viewer));
50 | }
51 |
52 | private void 清空RoiButton_OnClick(object sender, RoutedEventArgs e)
53 | {
54 | Viewer.ClearRoi();
55 | }
56 | }
57 | }
--------------------------------------------------------------------------------
/ImageViewerDemo.DotSettings:
--------------------------------------------------------------------------------
1 |
2 | True
--------------------------------------------------------------------------------
/ImageViewerDemo.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.30320.27
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ImageViewerDemo", "ImageViewerDemo\ImageViewerDemo.csproj", "{C7182CB4-818A-460B-9E70-AB8DAD659995}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ImageViewer", "ImageViewer\ImageViewer.csproj", "{2F3A223E-5B79-4EA6-A93B-2AF198FF5D00}"
9 | EndProject
10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RenderTransformImageViewerDemo", "RenderTransformImageViewerDemo\RenderTransformImageViewerDemo.csproj", "{8AD96D67-E117-43FA-8F84-7A4D36F95610}"
11 | EndProject
12 | Global
13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
14 | Debug|Any CPU = Debug|Any CPU
15 | Release|Any CPU = Release|Any CPU
16 | EndGlobalSection
17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
18 | {C7182CB4-818A-460B-9E70-AB8DAD659995}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
19 | {C7182CB4-818A-460B-9E70-AB8DAD659995}.Debug|Any CPU.Build.0 = Debug|Any CPU
20 | {C7182CB4-818A-460B-9E70-AB8DAD659995}.Release|Any CPU.ActiveCfg = Release|Any CPU
21 | {C7182CB4-818A-460B-9E70-AB8DAD659995}.Release|Any CPU.Build.0 = Release|Any CPU
22 | {2F3A223E-5B79-4EA6-A93B-2AF198FF5D00}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
23 | {2F3A223E-5B79-4EA6-A93B-2AF198FF5D00}.Debug|Any CPU.Build.0 = Debug|Any CPU
24 | {2F3A223E-5B79-4EA6-A93B-2AF198FF5D00}.Release|Any CPU.ActiveCfg = Release|Any CPU
25 | {2F3A223E-5B79-4EA6-A93B-2AF198FF5D00}.Release|Any CPU.Build.0 = Release|Any CPU
26 | {8AD96D67-E117-43FA-8F84-7A4D36F95610}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27 | {8AD96D67-E117-43FA-8F84-7A4D36F95610}.Debug|Any CPU.Build.0 = Debug|Any CPU
28 | {8AD96D67-E117-43FA-8F84-7A4D36F95610}.Release|Any CPU.ActiveCfg = Release|Any CPU
29 | {8AD96D67-E117-43FA-8F84-7A4D36F95610}.Release|Any CPU.Build.0 = Release|Any CPU
30 | EndGlobalSection
31 | GlobalSection(SolutionProperties) = preSolution
32 | HideSolutionNode = FALSE
33 | EndGlobalSection
34 | GlobalSection(ExtensibilityGlobals) = postSolution
35 | SolutionGuid = {CD210984-D116-431C-9283-CCF0510D2EBC}
36 | EndGlobalSection
37 | EndGlobal
38 |
--------------------------------------------------------------------------------
/ImageViewerDemo/App.xaml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
--------------------------------------------------------------------------------
/ImageViewerDemo/App.xaml.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 |
3 | namespace ImageViewerDemo
4 | {
5 | ///
6 | /// Interaction logic for App.xaml
7 | ///
8 | public partial class App : Application
9 | {
10 | }
11 | }
--------------------------------------------------------------------------------
/ImageViewerDemo/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 |
3 | [assembly: ThemeInfo(
4 | ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
5 | //(used if a resource is not found in the page,
6 | // or application resource dictionaries)
7 | ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
8 | //(used if a resource is not found in the page,
9 | // app, or any theme specific resource dictionaries)
10 | )]
--------------------------------------------------------------------------------
/ImageViewerDemo/ConsoleExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace ImageViewerDemo
4 | {
5 | public static class ConsoleExtensions
6 | {
7 | public static void ConsoleSplitLine(char splitLineChar = '_',
8 | ConsoleColor foregroundColor = ConsoleColor.Gray,
9 | ConsoleColor backgroundColor = ConsoleColor.Black)
10 | {
11 | int width = Console.WindowWidth;
12 | new string(splitLineChar, width - 1).WriteLine(foregroundColor,
13 | backgroundColor);
14 | }
15 | public static void WriteLine(this T t,
16 | ConsoleColor foregroundColor = ConsoleColor.Gray,
17 | ConsoleColor backgroundColor = ConsoleColor.Black)
18 | {
19 | ConsoleColor backgroundBuff = Console.BackgroundColor;
20 | ConsoleColor foregroundBuff = Console.ForegroundColor;
21 | Console.BackgroundColor = backgroundColor;
22 | Console.ForegroundColor = foregroundColor;
23 | Console.WriteLine(t);
24 | Console.BackgroundColor = backgroundBuff;
25 | Console.ForegroundColor = foregroundBuff;
26 | }
27 | }
28 | }
--------------------------------------------------------------------------------
/ImageViewerDemo/FodyWeavers.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/ImageViewerDemo/FodyWeavers.xsd:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 | Used to control if the On_PropertyName_Changed feature is enabled.
12 |
13 |
14 |
15 |
16 | Used to change the name of the method that fires the notify event. This is a string that accepts multiple values in a comma separated form.
17 |
18 |
19 |
20 |
21 | Used to control if equality checks should be inserted. If false, equality checking will be disabled for the project.
22 |
23 |
24 |
25 |
26 | Used to control if equality checks should use the Equals method resolved from the base class.
27 |
28 |
29 |
30 |
31 | Used to control if equality checks should use the static Equals method resolved from the base class.
32 |
33 |
34 |
35 |
36 | Used to turn off build warnings from this weaver.
37 |
38 |
39 |
40 |
41 | Used to turn off build warnings about mismatched On_PropertyName_Changed methods.
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 | 'true' to run assembly verification (PEVerify) on the target assembly after all weavers have been executed.
50 |
51 |
52 |
53 |
54 | A comma-separated list of error codes that can be safely ignored in assembly verification.
55 |
56 |
57 |
58 |
59 | 'false' to turn off automatic generation of the XML Schema file.
60 |
61 |
62 |
63 |
64 |
--------------------------------------------------------------------------------
/ImageViewerDemo/ImageViewerDemo.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net5.0
6 | true
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/ImageViewerDemo/MainWindow.xaml:
--------------------------------------------------------------------------------
1 |
13 |
14 |
15 |
16 |
17 |
18 |
33 |
34 |
35 |
36 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
49 |
53 |
57 |
61 |
65 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/ImageViewerDemo/MainWindow.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Immutable;
3 | using System.ComponentModel;
4 | using System.Diagnostics.CodeAnalysis;
5 | using System.Linq;
6 | using System.Runtime.CompilerServices;
7 | using System.Windows;
8 | using System.Windows.Controls;
9 | using System.Windows.Controls.Primitives;
10 | using System.Windows.Input;
11 | using System.Windows.Media;
12 | using System.Windows.Media.Imaging;
13 | using System.Windows.Shapes;
14 | using JetBrains.Annotations;
15 |
16 | namespace ImageViewerDemo
17 | {
18 | ///
19 | /// Interaction logic for MainWindow.xaml
20 | ///
21 | [SuppressMessage("ReSharper", "PossibleNullReferenceException")]
22 | public partial class MainWindow : INotifyPropertyChanged
23 | {
24 | private Path _buffPath;
25 | private Point _buffPosition;
26 | private Image _image;
27 |
28 | public MainWindow()
29 | {
30 | InitializeComponent();
31 | }
32 |
33 | public event PropertyChangedEventHandler PropertyChanged;
34 | public bool IsMove { get; set; }
35 | public bool IsRectangle { get; set; }
36 | public bool IsScale { get; set; }
37 | public double Scale { get; private set; } = 1;
38 |
39 | [NotifyPropertyChangedInvocator]
40 | protected virtual void OnPropertyChanged(
41 | [CallerMemberName] string propertyName = null)
42 | {
43 | PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
44 | }
45 |
46 | private static bool IsMouseButtonDown(MouseEventArgs e)
47 | {
48 | return e.LeftButton == MouseButtonState.Pressed ||
49 | e.RightButton == MouseButtonState.Pressed;
50 | }
51 |
52 | private void InCanvas_OnLoaded(object sender, RoutedEventArgs e)
53 | {
54 | var canvas = sender as Canvas;
55 | var bitmapImage = new BitmapImage(new Uri(
56 | @"C:\Users\Taurus Zhou\Downloads\b4979074ad8058e0e7d2c89a6e8d930b.jpg"));
57 | _image = new Image {Source = bitmapImage};
58 | canvas.Children.Add(_image);
59 | canvas.Width = bitmapImage.Width * 1000;
60 | canvas.Height = bitmapImage.Height * 1000;
61 | double x = canvas.Width / 2 - bitmapImage.Width / 2;
62 | double y = canvas.Height / 2 - bitmapImage.Height / 2;
63 | _image.SetXY(x, y);
64 | canvas.SetXY(-x, -y);
65 | }
66 |
67 | private void InCanvas_OnMouseDown(object sender, MouseButtonEventArgs e)
68 | {
69 | if (IsRectangle && IsMouseButtonDown(e))
70 | {
71 | _buffPosition = e.GetPosition((IInputElement) sender);
72 | _buffPath = default;
73 | }
74 | }
75 |
76 | private void InCanvas_OnMouseMove(object sender, MouseEventArgs e)
77 | {
78 | if (IsRectangle && IsMouseButtonDown(e))
79 | {
80 | var canvas = sender as Canvas;
81 | Point position = e.GetPosition(canvas);
82 | Vector vector = position - _buffPosition;
83 | var buffRect = new Rect(_buffPosition, vector);
84 | double x = buffRect.X;
85 | double y = buffRect.Y;
86 | var rect = new Rect(buffRect.Size);
87 | var rectangleGeometry = new RectangleGeometry(rect);
88 | var path = new Path
89 | {
90 | Data = rectangleGeometry,
91 | Stroke = Brushes.DarkRed,
92 | StrokeThickness = 5
93 | };
94 | if (_buffPath == null)
95 | {
96 | _buffPath = path;
97 | canvas.Children.Add(_buffPath);
98 | }
99 | else
100 | {
101 | Path single = canvas.Children.OfType()
102 | .Single(path1 => path1 == _buffPath);
103 | single.SetFrom(path);
104 | }
105 |
106 | _buffPath.SetXY(x, y);
107 | }
108 | }
109 |
110 | private void OutCanvas_OnMouseDown(object sender, MouseButtonEventArgs e)
111 | {
112 | if (IsMove && IsMouseButtonDown(e))
113 | _buffPosition = e.GetPosition((IInputElement) sender);
114 | }
115 |
116 | private void OutCanvas_OnMouseMove(object sender, MouseEventArgs e)
117 | {
118 | if (IsMove && IsMouseButtonDown(e))
119 | {
120 | Point position = e.GetPosition((IInputElement) sender);
121 | Vector vector = position - _buffPosition;
122 | (double x, double y) = InCanvas.GetXY();
123 | InCanvas.SetXY(vector.X + x, vector.Y + y);
124 | _buffPosition = position;
125 | }
126 | }
127 |
128 | private void OutCanvas_OnMouseWheel(object sender, MouseWheelEventArgs e)
129 | {
130 | if (IsScale)
131 | {
132 | const double constScale = 0.005;
133 | if (e.Delta > 0)
134 | {
135 | Scale += constScale;
136 | }
137 | else
138 | {
139 | double d = Scale - constScale;
140 | if (d > 0)
141 | Scale = d;
142 | }
143 |
144 | InCanvas.RenderTransform = new ScaleTransform(Scale, Scale);
145 | }
146 | }
147 |
148 | private void ToggleButtons_OnClick(object sender, RoutedEventArgs e)
149 | {
150 | var toggleButton = sender as ToggleButton;
151 | WrapPanel wrapPanel = toggleButton.Parent as WrapPanel;
152 | foreach (ToggleButton button in wrapPanel.Children.OfType())
153 | if (button != toggleButton)
154 | button.IsChecked = false;
155 | }
156 |
157 | private void 获取Image相对于InCanvas的位置Button_OnClick(object sender,
158 | RoutedEventArgs e)
159 | {
160 | double x = _image.RenderSize.Width;
161 | double y = _image.RenderSize.Height;
162 | ConsoleExtensions.ConsoleSplitLine(foregroundColor: ConsoleColor.DarkRed);
163 | _image.TranslatePoint(new Point(0, 0), InCanvas).WriteLine();
164 | _image.TranslatePoint(new Point(x, 0), InCanvas).WriteLine();
165 | _image.TranslatePoint(new Point(0, y), InCanvas).WriteLine();
166 | _image.TranslatePoint(new Point(x, y), InCanvas).WriteLine();
167 | ConsoleExtensions.ConsoleSplitLine(foregroundColor: ConsoleColor.DarkRed);
168 | }
169 |
170 | private void 获取InCanvas相对于OutCanvas的位置Button_OnClick(object sender,
171 | RoutedEventArgs e)
172 | {
173 | double x = InCanvas.RenderSize.Width;
174 | double y = InCanvas.RenderSize.Height;
175 | ConsoleExtensions.ConsoleSplitLine(foregroundColor: ConsoleColor.DarkRed);
176 | InCanvas.TranslatePoint(new Point(0, 0), OutCanvas).WriteLine();
177 | InCanvas.TranslatePoint(new Point(x, 0), OutCanvas).WriteLine();
178 | InCanvas.TranslatePoint(new Point(0, y), OutCanvas).WriteLine();
179 | InCanvas.TranslatePoint(new Point(x, y), OutCanvas).WriteLine();
180 | ConsoleExtensions.ConsoleSplitLine(foregroundColor: ConsoleColor.DarkRed);
181 | }
182 |
183 | private void 删除所有的roiButton_OnClick(object sender, RoutedEventArgs e)
184 | {
185 | foreach (Path path in InCanvas.Children.OfType().ToImmutableArray())
186 | {
187 | InCanvas.Children.Remove(path);
188 | }
189 | }
190 |
191 | private void 获取所有的roi与Image的相对位置Button_OnClick(object sender, RoutedEventArgs e)
192 | {
193 | ConsoleExtensions.ConsoleSplitLine(foregroundColor: ConsoleColor.Red);
194 | foreach (Path path in InCanvas.Children.OfType())
195 | {
196 | path.TranslatePoint(new Point(0, 0), _image).WriteLine();
197 | }
198 |
199 | ConsoleExtensions.ConsoleSplitLine(foregroundColor: ConsoleColor.Red);
200 | }
201 |
202 | private void 旋转所有的roiButton_OnClick(object sender, RoutedEventArgs e)
203 | {
204 | foreach (Path path in InCanvas.Children.OfType())
205 | {
206 | {
207 | (double x, double y) valueTuple = path.GetXY();
208 | valueTuple.WriteLine();
209 | }
210 | path.RenderTransformOrigin = new Point(0.5, 0.5);
211 | path.RenderTransform = new RotateTransform(30);
212 | {
213 | (double x, double y) valueTuple = path.GetXY();
214 | valueTuple.WriteLine();
215 | }
216 | }
217 | }
218 | }
219 | }
--------------------------------------------------------------------------------
/ImageViewerDemo/PathExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.Windows.Shapes;
2 |
3 | namespace ImageViewerDemo
4 | {
5 | public static class PathExtensions
6 | {
7 | public static void SetFrom(this Path source, Path path)
8 | {
9 | source.Data = path.Data;
10 | source.Stroke = path.Stroke;
11 | source.StrokeThickness = path.StrokeThickness;
12 | }
13 | }
14 | }
--------------------------------------------------------------------------------
/ImageViewerDemo/UIElementExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 | using System.Windows.Controls;
3 |
4 | namespace ImageViewerDemo
5 | {
6 | public static class UIElementExtensions
7 | {
8 | public static double GetX(this UIElement uiElement)
9 | {
10 | double d = Canvas.GetLeft(uiElement);
11 | return double.IsNaN(d) ? 0 : d;
12 | }
13 |
14 | public static (double x, double y) GetXY(this UIElement uiElement)
15 | {
16 | double x = uiElement.GetX();
17 | double y = uiElement.GetY();
18 | return (x, y);
19 | }
20 |
21 | public static double GetY(this UIElement uiElement)
22 | {
23 | double d = Canvas.GetTop(uiElement);
24 | return double.IsNaN(d) ? 0 : d;
25 | }
26 |
27 | public static void SetX(this UIElement uiElement, double length)
28 | {
29 | Canvas.SetLeft(uiElement, length);
30 | }
31 |
32 | public static void SetXY(this UIElement uiElement, double x, double y)
33 | {
34 | uiElement.SetX(x);
35 | uiElement.SetY(y);
36 | }
37 |
38 | public static void SetY(this UIElement uiElement, double length)
39 | {
40 | Canvas.SetTop(uiElement, length);
41 | }
42 | }
43 | }
--------------------------------------------------------------------------------
/ReadMe.md:
--------------------------------------------------------------------------------
1 | # 使用仿射变换实现Image Viewer控件原理
2 |
3 | WPF控件的属性`RenderTransform`为`System.Windows.Media.Transform`类型,该类的基本功能为实现二维平面的仿射变换(平移、旋转、缩放、倾斜的组合变换)。
4 |
5 | `System.Windows.Media.Transform`的底层包含了一个`System.Windows.Media.Matrix`的结构体,该结构体表示的结构为3*3的仿射变换矩阵,并且该结构体还提供了一些方法,用于计算进行仿射变换后新的仿射变换矩阵。例如:平移`public void Translate (double offsetX, double offsetY);`、旋转`public void Rotate (double angle);`、倾斜`public void Skew (double skewX, double skewY);`、缩放`public void Scale (double scaleX, double scaleY);`。
6 |
7 | 首先通过调用WPF控件的`RenderTransform`的`Value`获取控件当前用于渲染的`System.Windows.Media.Matrix`,调用该`System.Windows.Media.Matrix`的各种仿射变换方法,然后构造一个新的`System.Windows.Media.MatrixTransform`类,并在`System.Windows.Media.MatrixTransform`类的构造函数中填入刚刚的`System.Windows.Media.Matrix`对象。并且将这个新构造的`System.Windows.Media.MatrixTransform`对象赋值给WPF控件的`RenderTransform`的属性。
8 |
9 | 通过调用控件的`public System.Windows.Point TranslatePoint (System.Windows.Point point, System.Windows.UIElement relativeTo);`方法得到本控件的某个坐标在其他控件的坐标是多少。
--------------------------------------------------------------------------------
/RenderTransformImageViewerDemo/App.xaml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/RenderTransformImageViewerDemo/App.xaml.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 |
3 | namespace RenderTransformImageViewerDemo
4 | {
5 | ///
6 | /// Interaction logic for App.xaml
7 | ///
8 | public partial class App : Application
9 | {
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/RenderTransformImageViewerDemo/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 |
3 | [assembly: ThemeInfo(
4 | ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
5 | //(used if a resource is not found in the page,
6 | // or application resource dictionaries)
7 | ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
8 | //(used if a resource is not found in the page,
9 | // app, or any theme specific resource dictionaries)
10 | )]
11 |
--------------------------------------------------------------------------------
/RenderTransformImageViewerDemo/DebugExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 |
3 | namespace RenderTransformImageViewerDemo
4 | {
5 | public static class DebugExtensions
6 | {
7 | public static void WriteLine(this T t)
8 | {
9 | Debug.WriteLine(t);
10 | }
11 | }
12 | }
--------------------------------------------------------------------------------
/RenderTransformImageViewerDemo/MainWindow.xaml:
--------------------------------------------------------------------------------
1 |
13 |
14 |
15 |
16 |
17 |
18 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
35 |
39 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/RenderTransformImageViewerDemo/MainWindow.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using System.Windows;
4 | using System.Windows.Controls;
5 | using System.Windows.Controls.Primitives;
6 | using System.Windows.Input;
7 | using System.Windows.Media;
8 | using System.Windows.Media.Imaging;
9 | using System.Windows.Shapes;
10 |
11 | namespace RenderTransformImageViewerDemo
12 | {
13 | ///
14 | /// Interaction logic for MainWindow.xaml
15 | ///
16 | public partial class MainWindow : Window
17 | {
18 | public static readonly DependencyProperty IsEllipseProperty =
19 | DependencyProperty.Register(nameof(IsEllipse),
20 | typeof(bool),
21 | typeof(MainWindow),
22 | new PropertyMetadata(default(bool)));
23 |
24 | public static readonly DependencyProperty IsMoveAndScaleProperty =
25 | DependencyProperty.Register(nameof(IsMoveAndScale),
26 | typeof(bool),
27 | typeof(MainWindow),
28 | new PropertyMetadata(default(bool)));
29 |
30 | public static readonly DependencyProperty IsRectangleProperty =
31 | DependencyProperty.Register(nameof(IsRectangle),
32 | typeof(bool),
33 | typeof(MainWindow),
34 | new PropertyMetadata(default(bool)));
35 |
36 | private Point _buffPosition;
37 | private Shape _buffShape;
38 | private bool _isEllipse;
39 | private bool _isMoveAndScale;
40 | private bool _isRectangle;
41 |
42 | public MainWindow()
43 | {
44 | InitializeComponent();
45 | }
46 |
47 | public bool IsEllipse
48 | {
49 | get => (bool) GetValue(IsEllipseProperty);
50 | set => SetValue(IsEllipseProperty, value);
51 | }
52 |
53 | public bool IsMoveAndScale
54 | {
55 | get => (bool) GetValue(IsMoveAndScaleProperty);
56 | set => SetValue(IsMoveAndScaleProperty, value);
57 | }
58 |
59 | public bool IsRectangle
60 | {
61 | get => (bool) GetValue(IsRectangleProperty);
62 | set => SetValue(IsRectangleProperty, value);
63 | }
64 |
65 | private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
66 | {
67 | Ellipse[] ellipses = Canvas.Children.OfType()
68 | .Where(ellipse => ellipse.Fill == Brushes.Black)
69 | .ToArray();
70 | foreach (Ellipse ellipsis in ellipses)
71 | Canvas.Children.Remove(ellipsis);
72 | foreach (Rectangle rectangle in Canvas.Children.OfType()
73 | .ToHashSet())
74 | {
75 | Point[] points =
76 | {
77 | new Point(0, 0),
78 | new Point(0, rectangle.Height),
79 | new Point(rectangle.Width, 0),
80 | new Point(rectangle.Width, rectangle.Height),
81 | };
82 | foreach (Point point in points)
83 | {
84 | Point translatePoint = rectangle.TranslatePoint(point, Canvas);
85 | var ellipse = new Ellipse()
86 | {
87 | Width = 10,
88 | Height = 10,
89 | Fill = Brushes.Black,
90 | Stroke = Brushes.GreenYellow,
91 | StrokeThickness = 2
92 | };
93 | Matrix matrix = ellipse.RenderTransform.Value;
94 | matrix.Translate(translatePoint.X - 5, translatePoint.Y - 5);
95 | ellipse.RenderTransform = new MatrixTransform(matrix);
96 | Canvas.Children.Add(ellipse);
97 | }
98 |
99 | Canvas.Children.Remove(rectangle);
100 | Canvas.Children.Add(rectangle);
101 | }
102 |
103 | foreach (Ellipse element in Canvas.Children.OfType()
104 | .Where(ellipse => ellipse.Fill != Brushes.Black)
105 | .ToHashSet())
106 | {
107 | Point[] points =
108 | {
109 | new Point(0, 0),
110 | new Point(0, element.Height),
111 | new Point(element.Width, 0),
112 | new Point(element.Width, element.Height),
113 | };
114 | foreach (Point point in points)
115 | {
116 | Point translatePoint = element.TranslatePoint(point, Canvas);
117 | var ellipse = new Ellipse()
118 | {
119 | Width = 10,
120 | Height = 10,
121 | Fill = Brushes.Black,
122 | Stroke = Brushes.GreenYellow,
123 | StrokeThickness = 2
124 | };
125 | Matrix matrix = ellipse.RenderTransform.Value;
126 | matrix.Translate(translatePoint.X - 5, translatePoint.Y - 5);
127 | ellipse.RenderTransform = new MatrixTransform(matrix);
128 | Canvas.Children.Add(ellipse);
129 | }
130 |
131 | Canvas.Children.Remove(element);
132 | Canvas.Children.Add(element);
133 | }
134 | }
135 |
136 | private void Image_OnLoaded(object sender, RoutedEventArgs e)
137 | {
138 | BitmapImage bitmapImage = new BitmapImage(new Uri(
139 | @"C:\Users\Taurus Zhou\Pictures\Saved Pictures\2c2864bc80e702b9f3f715a390782b18.jpg",
140 | UriKind.Absolute));
141 | int pixelWidth = bitmapImage.PixelWidth;
142 | int pixelHeight = bitmapImage.PixelHeight;
143 | Image.Width = pixelWidth;
144 | Image.Height = pixelHeight;
145 | Image.Source = bitmapImage;
146 | }
147 |
148 | private void ToggleButtons_OnClick(object sender, RoutedEventArgs e)
149 | {
150 | var toggleButton = (ToggleButton) sender;
151 | var wrapPanel = (WrapPanel) toggleButton.Parent;
152 | foreach (ToggleButton button in wrapPanel.Children.OfType()
153 | .ToHashSet()
154 | .Where(button => button != toggleButton))
155 | {
156 | button.IsChecked = false;
157 | }
158 | }
159 |
160 | private void UIElement_OnMouseDown(object sender, MouseButtonEventArgs e)
161 | {
162 | if (IsMoveAndScale)
163 | {
164 | var grid = (Grid) sender;
165 | if (grid.CaptureMouse() == false)
166 | {
167 | throw new Exception("未能成功捕获鼠标");
168 | }
169 |
170 | Point position = e.GetPosition(grid);
171 | _buffPosition = position;
172 | _isMoveAndScale = true;
173 | }
174 |
175 | if (IsRectangle)
176 | {
177 | var grid = (Grid) sender;
178 | if (grid.CaptureMouse() == false)
179 | {
180 | throw new Exception("未能成功捕获鼠标");
181 | }
182 |
183 | Point position = e.GetPosition(Canvas);
184 | _buffPosition = position;
185 | _isRectangle = true;
186 | }
187 |
188 | if (IsEllipse)
189 | {
190 | var grid = (Grid) sender;
191 | if (grid.CaptureMouse() == false)
192 | {
193 | throw new Exception("未能成功捕获鼠标");
194 | }
195 |
196 | Point position = e.GetPosition(Canvas);
197 | _buffPosition = position;
198 | _isEllipse = true;
199 | }
200 | }
201 |
202 | private void UIElement_OnMouseMove(object sender, MouseEventArgs e)
203 | {
204 | if (IsMoveAndScale && _isMoveAndScale)
205 | {
206 | Matrix matrix = Canvas.RenderTransform.Value;
207 | Point position = e.GetPosition((IInputElement) sender);
208 | Vector vector = position - _buffPosition;
209 | matrix.Translate(vector.X, vector.Y);
210 | Canvas.RenderTransform = new MatrixTransform(matrix);
211 | _buffPosition = position;
212 | }
213 |
214 | if (IsRectangle && _isRectangle)
215 | {
216 | Point position = e.GetPosition(Canvas);
217 | Vector vector = position - _buffPosition;
218 | var rect = new Rect(_buffPosition, vector);
219 | var rectangle = new Rectangle()
220 | {
221 | Width = rect.Width,
222 | Height = rect.Height,
223 | Stroke = Brushes.Red,
224 | StrokeThickness = 3
225 | };
226 | Matrix matrix = rectangle.RenderTransform.Value;
227 | matrix.Translate(rect.X, rect.Y);
228 | rectangle.RenderTransform = new MatrixTransform(matrix);
229 | if (_buffShape != null)
230 | {
231 | Canvas.Children.Remove(_buffShape);
232 | }
233 |
234 | _buffShape = rectangle;
235 | Canvas.Children.Add(_buffShape);
236 | }
237 |
238 | if (IsEllipse && _isEllipse)
239 | {
240 | Point position = e.GetPosition(Canvas);
241 | Vector vector = position - _buffPosition;
242 | var ellipse = new Ellipse()
243 | {
244 | Width = vector.Length * 2,
245 | Height = vector.Length * 2,
246 | Stroke = Brushes.Red,
247 | StrokeThickness = 3
248 | };
249 | Matrix matrix = ellipse.RenderTransform.Value;
250 | matrix.Translate(_buffPosition.X - ellipse.Width / 2,
251 | _buffPosition.Y - ellipse.Height / 2);
252 | ellipse.RenderTransform = new MatrixTransform(matrix);
253 | if (_buffShape != null)
254 | {
255 | Canvas.Children.Remove(_buffShape);
256 | }
257 |
258 | _buffShape = ellipse;
259 | Canvas.Children.Add(_buffShape);
260 | }
261 | }
262 |
263 | private void UIElement_OnMouseUp(object sender, MouseButtonEventArgs e)
264 | {
265 | if (IsMoveAndScale)
266 | {
267 | Mouse.Capture(default);
268 | _isMoveAndScale = false;
269 | }
270 |
271 | if (IsRectangle)
272 | {
273 | Mouse.Capture(default);
274 | _isRectangle = false;
275 | _buffShape = default;
276 | }
277 |
278 | if (IsEllipse)
279 | {
280 | Mouse.Capture(default);
281 | _isEllipse = false;
282 | _buffShape = default;
283 | }
284 | }
285 |
286 | private void UIElement_OnMouseWheel(object sender, MouseWheelEventArgs e)
287 | {
288 | if (IsMoveAndScale)
289 | {
290 | double scale = e.Delta > 0 ? 1 + 0.1 : 1 - 0.1;
291 | Matrix matrix = Canvas.RenderTransform.Value;
292 | Point position = e.GetPosition((IInputElement) sender);
293 | matrix.ScaleAt(scale, scale, position.X, position.Y);
294 | Canvas.RenderTransform = new MatrixTransform(matrix);
295 | }
296 | }
297 | }
298 | }
--------------------------------------------------------------------------------
/RenderTransformImageViewerDemo/RenderTransformImageViewerDemo.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | WinExe
5 | netcoreapp3.1
6 | true
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------