├── .gitignore
├── LICENSE
├── README.md
├── UI-Cropping-Image-Library
├── CroppingImageLibrary.SampleApp
│ ├── App.config
│ ├── App.xaml
│ ├── App.xaml.cs
│ ├── CroppingImageLibrary.SampleApp.csproj
│ ├── CroppingWindow.xaml
│ ├── CroppingWindow.xaml.cs
│ ├── MainWindow.xaml
│ ├── MainWindow.xaml.cs
│ └── Properties
│ │ ├── AssemblyInfo.cs
│ │ ├── Resources.Designer.cs
│ │ ├── Resources.resx
│ │ ├── Settings.Designer.cs
│ │ └── Settings.settings
├── CroppingImageLibrary
│ ├── CropToolControl.xaml
│ ├── CropToolControl.xaml.cs
│ ├── CroppingImageLibrary.csproj
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ └── Services
│ │ ├── CropAdorner.cs
│ │ ├── CropService.cs
│ │ ├── State
│ │ ├── CompleteState.cs
│ │ ├── CreateState.cs
│ │ ├── DragState.cs
│ │ ├── IToolState.cs
│ │ └── Position.cs
│ │ └── Tools
│ │ ├── CropShape.cs
│ │ ├── CropTool.cs
│ │ ├── ShadeTool.cs
│ │ ├── TextTool.cs
│ │ └── ThumbTool.cs
└── UI-Cropping-Image-Library.sln
├── cropped-demo.png
├── cropped-result-info.png
└── cropped-result.png
/.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 | *.suo
8 | *.user
9 | *.userosscache
10 | *.sln.docstates
11 |
12 | # User-specific files (MonoDevelop/Xamarin Studio)
13 | *.userprefs
14 |
15 | # Build results
16 | [Dd]ebug/
17 | [Dd]ebugPublic/
18 | [Rr]elease/
19 | [Rr]eleases/
20 | x64/
21 | x86/
22 | bld/
23 | [Bb]in/
24 | [Oo]bj/
25 | [Ll]og/
26 |
27 | # Visual Studio 2015 cache/options directory
28 | .vs/
29 | # Uncomment if you have tasks that create the project's static files in wwwroot
30 | #wwwroot/
31 |
32 | # MSTest test Results
33 | [Tt]est[Rr]esult*/
34 | [Bb]uild[Ll]og.*
35 |
36 | # NUNIT
37 | *.VisualState.xml
38 | TestResult.xml
39 |
40 | # Build Results of an ATL Project
41 | [Dd]ebugPS/
42 | [Rr]eleasePS/
43 | dlldata.c
44 |
45 | # .NET Core
46 | project.lock.json
47 | project.fragment.lock.json
48 | artifacts/
49 | **/Properties/launchSettings.json
50 |
51 | *_i.c
52 | *_p.c
53 | *_i.h
54 | *.ilk
55 | *.meta
56 | *.obj
57 | *.pch
58 | *.pdb
59 | *.pgc
60 | *.pgd
61 | *.rsp
62 | *.sbr
63 | *.tlb
64 | *.tli
65 | *.tlh
66 | *.tmp
67 | *.tmp_proj
68 | *.log
69 | *.vspscc
70 | *.vssscc
71 | .builds
72 | *.pidb
73 | *.svclog
74 | *.scc
75 |
76 | # Chutzpah Test files
77 | _Chutzpah*
78 |
79 | # Visual C++ cache files
80 | ipch/
81 | *.aps
82 | *.ncb
83 | *.opendb
84 | *.opensdf
85 | *.sdf
86 | *.cachefile
87 | *.VC.db
88 | *.VC.VC.opendb
89 |
90 | # Visual Studio profiler
91 | *.psess
92 | *.vsp
93 | *.vspx
94 | *.sap
95 |
96 | # TFS 2012 Local Workspace
97 | $tf/
98 |
99 | # Guidance Automation Toolkit
100 | *.gpState
101 |
102 | # ReSharper is a .NET coding add-in
103 | _ReSharper*/
104 | *.[Rr]e[Ss]harper
105 | *.DotSettings.user
106 |
107 | # JustCode is a .NET coding add-in
108 | .JustCode
109 |
110 | # TeamCity is a build add-in
111 | _TeamCity*
112 |
113 | # DotCover is a Code Coverage Tool
114 | *.dotCover
115 |
116 | # Visual Studio code coverage results
117 | *.coverage
118 | *.coveragexml
119 |
120 | # NCrunch
121 | _NCrunch_*
122 | .*crunch*.local.xml
123 | nCrunchTemp_*
124 |
125 | # MightyMoose
126 | *.mm.*
127 | AutoTest.Net/
128 |
129 | # Web workbench (sass)
130 | .sass-cache/
131 |
132 | # Installshield output folder
133 | [Ee]xpress/
134 |
135 | # DocProject is a documentation generator add-in
136 | DocProject/buildhelp/
137 | DocProject/Help/*.HxT
138 | DocProject/Help/*.HxC
139 | DocProject/Help/*.hhc
140 | DocProject/Help/*.hhk
141 | DocProject/Help/*.hhp
142 | DocProject/Help/Html2
143 | DocProject/Help/html
144 |
145 | # Click-Once directory
146 | publish/
147 |
148 | # Publish Web Output
149 | *.[Pp]ublish.xml
150 | *.azurePubxml
151 | # TODO: Comment the next line if you want to checkin your web deploy settings
152 | # but database connection strings (with potential passwords) will be unencrypted
153 | *.pubxml
154 | *.publishproj
155 |
156 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
157 | # checkin your Azure Web App publish settings, but sensitive information contained
158 | # in these scripts will be unencrypted
159 | PublishScripts/
160 |
161 | # NuGet Packages
162 | *.nupkg
163 | # The packages folder can be ignored because of Package Restore
164 | **/packages/*
165 | # except build/, which is used as an MSBuild target.
166 | !**/packages/build/
167 | # Uncomment if necessary however generally it will be regenerated when needed
168 | #!**/packages/repositories.config
169 | # NuGet v3's project.json files produces more ignorable files
170 | *.nuget.props
171 | *.nuget.targets
172 |
173 | # Microsoft Azure Build Output
174 | csx/
175 | *.build.csdef
176 |
177 | # Microsoft Azure Emulator
178 | ecf/
179 | rcf/
180 |
181 | # Windows Store app package directories and files
182 | AppPackages/
183 | BundleArtifacts/
184 | Package.StoreAssociation.xml
185 | _pkginfo.txt
186 |
187 | # Visual Studio cache files
188 | # files ending in .cache can be ignored
189 | *.[Cc]ache
190 | # but keep track of directories ending in .cache
191 | !*.[Cc]ache/
192 |
193 | # Others
194 | ClientBin/
195 | ~$*
196 | *~
197 | *.dbmdl
198 | *.dbproj.schemaview
199 | *.jfm
200 | *.pfx
201 | *.publishsettings
202 | orleans.codegen.cs
203 |
204 | # Since there are multiple workflows, uncomment next line to ignore bower_components
205 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
206 | #bower_components/
207 |
208 | # RIA/Silverlight projects
209 | Generated_Code/
210 |
211 | # Backup & report files from converting an old project file
212 | # to a newer Visual Studio version. Backup files are not needed,
213 | # because we have git ;-)
214 | _UpgradeReport_Files/
215 | Backup*/
216 | UpgradeLog*.XML
217 | UpgradeLog*.htm
218 |
219 | # SQL Server files
220 | *.mdf
221 | *.ldf
222 | *.ndf
223 |
224 | # Business Intelligence projects
225 | *.rdl.data
226 | *.bim.layout
227 | *.bim_*.settings
228 |
229 | # Microsoft Fakes
230 | FakesAssemblies/
231 |
232 | # GhostDoc plugin setting file
233 | *.GhostDoc.xml
234 |
235 | # Node.js Tools for Visual Studio
236 | .ntvs_analysis.dat
237 | node_modules/
238 |
239 | # Typescript v1 declaration files
240 | typings/
241 |
242 | # Visual Studio 6 build log
243 | *.plg
244 |
245 | # Visual Studio 6 workspace options file
246 | *.opt
247 |
248 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
249 | *.vbw
250 |
251 | # Visual Studio LightSwitch build output
252 | **/*.HTMLClient/GeneratedArtifacts
253 | **/*.DesktopClient/GeneratedArtifacts
254 | **/*.DesktopClient/ModelManifest.xml
255 | **/*.Server/GeneratedArtifacts
256 | **/*.Server/ModelManifest.xml
257 | _Pvt_Extensions
258 |
259 | # Paket dependency manager
260 | .paket/paket.exe
261 | paket-files/
262 |
263 | # FAKE - F# Make
264 | .fake/
265 |
266 | # JetBrains Rider
267 | .idea/
268 | *.sln.iml
269 |
270 | # CodeRush
271 | .cr/
272 |
273 | # Python Tools for Visual Studio (PTVS)
274 | __pycache__/
275 | *.pyc
276 |
277 | # Cake - Uncomment if you are using it
278 | # tools/**
279 | # !tools/packages.config
280 |
281 | # Telerik's JustMock configuration file
282 | *.jmconfig
283 |
284 | # BizTalk build output
285 | *.btp.cs
286 | *.btm.cs
287 | *.odx.cs
288 | *.xsd.cs
289 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 Dmitry
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # UI-Cropping-Image
2 | A simply UI cropping image library for WPF that use adroner layer. Some screenshots:
3 |
4 | Interface of sample app
5 |
6 |
7 |
8 | Cropping result image
9 |
10 |
11 |
12 | Cropping result image info
13 |
14 |
15 |
16 | # Main Workflow:
17 | 1. Load image
18 | 2. Select cropping area
19 | 3. Crop and save image
20 |
21 | # Main features:
22 | * Can draw/redraw cropping rectangle
23 | * Can move cropping rectangle
24 | * Can resize cropping rectangle
25 | * Shadow area outside of cropping rectangle
26 | * Show current size of cropping rectangle
27 |
28 |
29 | # Basic Setup
30 | XAML:
31 |
32 | In order to properly handle image size, set `SizeToContent ="WidthAndHeight"` to window.
33 | There is a custom user control CropToolControl.xaml, that holds all necessary elements to handle crop operation.
34 | Just add this ``
35 |
36 | Here is a example in CroppingWindow.xaml
37 | ```
38 |
46 |
47 |
48 | ```
49 | Code Behind:
50 | You need to pass image to user control, here is simple way describe in CroppingWindow.xaml.cs
51 | ```
52 | public partial class CroppingWindow : Window
53 | {
54 | public CroppingWindow()
55 | {
56 | InitializeComponent();
57 | }
58 |
59 | public CroppingWindow(BitmapImage bitmapImage)
60 | {
61 | InitializeComponent();
62 | // pass data to custom user control
63 | CropTool.SetImage(bitmapImage);
64 | }
65 | }
66 | ```
67 | This library return only crop area, not cropped image itself. You need to perform crop operation manually. To get crop area, call CropTool.CropService.GetCroppedArea()
68 |
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary.SampleApp/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary.SampleApp/App.xaml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary.SampleApp/App.xaml.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 |
3 | namespace CroppingImageLibrary.SampleApp
4 | {
5 | ///
6 | /// Interaction logic for App.xaml
7 | ///
8 | public partial class App : Application { }
9 | }
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary.SampleApp/CroppingImageLibrary.SampleApp.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {65C9DD8D-8B24-4EC1-A2B5-88FF42F46D01}
8 | WinExe
9 | CroppingImageLibrary.SampleApp
10 | CroppingImageLibrary.SampleApp
11 | v4.6.1
12 | 512
13 | {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
14 | 4
15 | true
16 | 8
17 |
18 |
19 | AnyCPU
20 | true
21 | full
22 | false
23 | bin\Debug\
24 | DEBUG;TRACE
25 | prompt
26 | 4
27 |
28 |
29 | AnyCPU
30 | pdbonly
31 | true
32 | bin\Release\
33 | TRACE
34 | prompt
35 | 4
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 | 4.0
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 | MSBuild:Compile
57 | Designer
58 |
59 |
60 | Designer
61 | MSBuild:Compile
62 |
63 |
64 | MSBuild:Compile
65 | Designer
66 |
67 |
68 | App.xaml
69 | Code
70 |
71 |
72 | CroppingWindow.xaml
73 |
74 |
75 | MainWindow.xaml
76 | Code
77 |
78 |
79 |
80 |
81 | Code
82 |
83 |
84 | True
85 | True
86 | Resources.resx
87 |
88 |
89 | True
90 | Settings.settings
91 | True
92 |
93 |
94 | ResXFileCodeGenerator
95 | Resources.Designer.cs
96 |
97 |
98 | SettingsSingleFileGenerator
99 | Settings.Designer.cs
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 | {AADA3516-FF2A-4C8D-AC3F-43C38ACB7BE4}
108 | CroppingImageLibrary
109 |
110 |
111 |
112 |
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary.SampleApp/CroppingWindow.xaml:
--------------------------------------------------------------------------------
1 |
9 |
10 |
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary.SampleApp/CroppingWindow.xaml.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 | using System.Windows.Media.Imaging;
3 |
4 | namespace CroppingImageLibrary.SampleApp
5 | {
6 | ///
7 | /// Interaction logic for CroppingWindow.xaml
8 | ///
9 | public partial class CroppingWindow : Window
10 | {
11 | public CroppingWindow()
12 | {
13 | InitializeComponent();
14 | }
15 |
16 | public CroppingWindow(BitmapImage bitmapImage)
17 | {
18 | InitializeComponent();
19 | // pass data to custom user control
20 | CropTool.SetImage(bitmapImage);
21 | }
22 | }
23 | }
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary.SampleApp/MainWindow.xaml:
--------------------------------------------------------------------------------
1 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary.SampleApp/MainWindow.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Drawing;
3 | using System.Windows;
4 | using System.Windows.Media.Imaging;
5 | using Microsoft.Win32;
6 |
7 | namespace CroppingImageLibrary.SampleApp
8 | {
9 | ///
10 | /// Interaction logic for MainWindow.xaml
11 | ///
12 | public partial class MainWindow
13 | {
14 | private CroppingWindow _croppingWindow;
15 | // private BitmapImage bitmapImage;
16 | private Bitmap sourceBitmap;
17 |
18 | public MainWindow()
19 | {
20 | InitializeComponent();
21 | Topmost = true;
22 | }
23 |
24 | private void Button_LoadImage(object sender, RoutedEventArgs e)
25 | {
26 | if (_croppingWindow != null)
27 | return;
28 | OpenFileDialog op = new OpenFileDialog();
29 | op.Title = "Select a picture";
30 | op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" + "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" + "Portable Network Graphic (*.png)|*.png";
31 | if (op.ShowDialog() == true)
32 | {
33 | sourceBitmap = new Bitmap(op.FileName);
34 | _croppingWindow = new CroppingWindow(new BitmapImage(new Uri(op.FileName)));
35 | _croppingWindow.Closed += (a, b) => _croppingWindow = null;
36 | _croppingWindow.Height = new BitmapImage(new Uri(op.FileName)).Height;
37 | _croppingWindow.Width = new BitmapImage(new Uri(op.FileName)).Width;
38 |
39 | _croppingWindow.Show();
40 | }
41 | }
42 |
43 | private void Button_SaveImage(object sender, RoutedEventArgs e)
44 | {
45 | var cropArea = _croppingWindow.CropTool.CropService.GetCroppedArea();
46 |
47 | System.Drawing.Rectangle cropRect = new System.Drawing.Rectangle((int) cropArea.CroppedRectAbsolute.X,
48 | (int) cropArea.CroppedRectAbsolute.Y, (int) cropArea.CroppedRectAbsolute.Width,
49 | (int) cropArea.CroppedRectAbsolute.Height);
50 |
51 | Bitmap target = new Bitmap(cropRect.Width, cropRect.Height);
52 |
53 | using (Graphics g = Graphics.FromImage(target))
54 | {
55 | g.DrawImage(sourceBitmap, new System.Drawing.Rectangle(0, 0, target.Width, target.Height),
56 | cropRect,
57 | GraphicsUnit.Pixel);
58 | }
59 |
60 | //save image to file
61 | SaveFileDialog dlg = new SaveFileDialog
62 | {
63 | FileName = "TestCropping", // Default file name
64 | DefaultExt = ".png", // Default file extension
65 | Filter = "Image png (.png)|*.png" // Filter files by extension
66 | };
67 |
68 | // Show save file dialog box
69 | bool? result = dlg.ShowDialog();
70 |
71 | // Process save file dialog box results
72 | if (result != true)
73 | return;
74 |
75 | // Save document
76 | string filename = dlg.FileName;
77 | target.Save(filename);
78 | }
79 | }
80 | }
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary.SampleApp/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.InteropServices;
3 | using System.Windows;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("CroppingImageLibrary.SampleApp")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("CroppingImageLibrary.SampleApp")]
13 | [assembly: AssemblyCopyright("Copyright © 2018")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | //In order to begin building localizable applications, set
23 | //CultureYouAreCodingWith in your .csproj file
24 | //inside a . For example, if you are using US english
25 | //in your source files, set the to en-US. Then uncomment
26 | //the NeutralResourceLanguage attribute below. Update the "en-US" in
27 | //the line below to match the UICulture setting in the project file.
28 |
29 | //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
30 |
31 |
32 | [assembly: ThemeInfo(
33 | ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
34 | //(used if a resource is not found in the page,
35 | // or application resource dictionaries)
36 | ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
37 | //(used if a resource is not found in the page,
38 | // app, or any theme specific resource dictionaries)
39 | )]
40 |
41 |
42 | // Version information for an assembly consists of the following four values:
43 | //
44 | // Major Version
45 | // Minor Version
46 | // Build Number
47 | // Revision
48 | //
49 | // You can specify all the values or you can default the Build and Revision Numbers
50 | // by using the '*' as shown below:
51 | // [assembly: AssemblyVersion("1.0.*")]
52 | [assembly: AssemblyVersion("1.0.0.0")]
53 | [assembly: AssemblyFileVersion("1.0.0.0")]
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary.SampleApp/Properties/Resources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.42000
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace CroppingImageLibrary.SampleApp.Properties
12 | {
13 |
14 |
15 | ///
16 | /// A strongly-typed resource class, for looking up localized strings, etc.
17 | ///
18 | // This class was auto-generated by the StronglyTypedResourceBuilder
19 | // class via a tool like ResGen or Visual Studio.
20 | // To add or remove a member, edit your .ResX file then rerun ResGen
21 | // with the /str option, or rebuild your VS project.
22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
25 | internal class Resources
26 | {
27 |
28 | private static global::System.Resources.ResourceManager resourceMan;
29 |
30 | private static global::System.Globalization.CultureInfo resourceCulture;
31 |
32 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
33 | internal Resources()
34 | {
35 | }
36 |
37 | ///
38 | /// Returns the cached ResourceManager instance used by this class.
39 | ///
40 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
41 | internal static global::System.Resources.ResourceManager ResourceManager
42 | {
43 | get
44 | {
45 | if ((resourceMan == null))
46 | {
47 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("CroppingImageLibrary.SampleApp.Properties.Resources", typeof(Resources).Assembly);
48 | resourceMan = temp;
49 | }
50 | return resourceMan;
51 | }
52 | }
53 |
54 | ///
55 | /// Overrides the current thread's CurrentUICulture property for all
56 | /// resource lookups using this strongly typed resource class.
57 | ///
58 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
59 | internal static global::System.Globalization.CultureInfo Culture
60 | {
61 | get
62 | {
63 | return resourceCulture;
64 | }
65 | set
66 | {
67 | resourceCulture = value;
68 | }
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary.SampleApp/Properties/Resources.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 | text/microsoft-resx
107 |
108 |
109 | 2.0
110 |
111 |
112 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
113 |
114 |
115 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary.SampleApp/Properties/Settings.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.42000
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace CroppingImageLibrary.SampleApp.Properties
12 | {
13 |
14 |
15 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
16 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
17 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
18 | {
19 |
20 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
21 |
22 | public static Settings Default
23 | {
24 | get
25 | {
26 | return defaultInstance;
27 | }
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary.SampleApp/Properties/Settings.settings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary/CropToolControl.xaml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
10 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary/CropToolControl.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Windows;
3 | using System.Windows.Controls;
4 | using System.Windows.Input;
5 | using System.Windows.Media.Imaging;
6 | using CroppingImageLibrary.Services;
7 |
8 | namespace CroppingImageLibrary
9 | {
10 | ///
11 | /// Interaction logic for CropToolControl.xaml
12 | ///
13 | public partial class CropToolControl : UserControl
14 | {
15 | public CropService CropService { get; private set; }
16 |
17 | public CropToolControl()
18 | {
19 | InitializeComponent();
20 | }
21 |
22 | private void RootGrid_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
23 | {
24 | CropService.Adorner.RaiseEvent(e);
25 | }
26 |
27 | private void RootGrid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
28 | {
29 | CropService.Adorner.RaiseEvent(e);
30 | }
31 |
32 | private void RootGrid_Loaded(object sender, RoutedEventArgs e)
33 | {
34 | CropService = new CropService(this);
35 | }
36 |
37 | public void SetImage(BitmapImage bitmapImage)
38 | {
39 | SourceImage.Source = bitmapImage;
40 | RootGrid.Height = bitmapImage.Height;
41 | RootGrid.Width = bitmapImage.Width;
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary/CroppingImageLibrary.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {AADA3516-FF2A-4C8D-AC3F-43C38ACB7BE4}
8 | Library
9 | Properties
10 | CroppingImageLibrary
11 | CroppingImageLibrary
12 | v4.6.1
13 | 512
14 | 8
15 |
16 |
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 |
25 |
26 | pdbonly
27 | true
28 | bin\Release\
29 | TRACE
30 | prompt
31 | 4
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 | CropToolControl.xaml
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 | MSBuild:Compile
69 | Designer
70 |
71 |
72 |
73 |
74 |
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.InteropServices;
3 |
4 | // General Information about an assembly is controlled through the following
5 | // set of attributes. Change these attribute values to modify the information
6 | // associated with an assembly.
7 | [assembly: AssemblyTitle("CroppingImageLibrary")]
8 | [assembly: AssemblyDescription("")]
9 | [assembly: AssemblyConfiguration("")]
10 | [assembly: AssemblyCompany("")]
11 | [assembly: AssemblyProduct("CroppingImageLibrary")]
12 | [assembly: AssemblyCopyright("Copyright © 2018")]
13 | [assembly: AssemblyTrademark("")]
14 | [assembly: AssemblyCulture("")]
15 |
16 | // Setting ComVisible to false makes the types in this assembly not visible
17 | // to COM components. If you need to access a type in this assembly from
18 | // COM, set the ComVisible attribute to true on that type.
19 | [assembly: ComVisible(false)]
20 |
21 | // The following GUID is for the ID of the typelib if this project is exposed to COM
22 | [assembly: Guid("aada3516-ff2a-4c8d-ac3f-43c38acb7be4")]
23 |
24 | // Version information for an assembly consists of the following four values:
25 | //
26 | // Major Version
27 | // Minor Version
28 | // Build Number
29 | // Revision
30 | //
31 | // You can specify all the values or you can default the Build and Revision Numbers
32 | // by using the '*' as shown below:
33 | // [assembly: AssemblyVersion("1.0.*")]
34 | [assembly: AssemblyVersion("1.0.0.0")]
35 | [assembly: AssemblyFileVersion("1.0.0.0")]
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary/Services/CropAdorner.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 | using System.Windows.Controls;
3 | using System.Windows.Documents;
4 | using System.Windows.Media;
5 |
6 | namespace CroppingImageLibrary.Services
7 | {
8 | internal class CropAdorner : Adorner
9 | {
10 | private readonly Canvas _overlayCanvas;
11 | private readonly VisualCollection _visualCollection;
12 |
13 | public CropAdorner(UIElement adornedElement, Canvas overlayCanvas) : base(adornedElement)
14 | {
15 | _overlayCanvas = overlayCanvas;
16 | _visualCollection = new VisualCollection(this);
17 | _visualCollection.Add(_overlayCanvas);
18 | }
19 |
20 | protected override int VisualChildrenCount => _visualCollection.Count;
21 |
22 | protected override Visual GetVisualChild(int index) => _visualCollection[index];
23 |
24 | protected override Size ArrangeOverride(Size size)
25 | {
26 | Size finalSize = base.ArrangeOverride(size);
27 | _overlayCanvas.Arrange(new Rect(0, 0, AdornedElement.RenderSize.Width, AdornedElement.RenderSize.Height));
28 | return finalSize;
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary/Services/CropService.cs:
--------------------------------------------------------------------------------
1 | using System.Diagnostics;
2 | using System.Windows;
3 | using System.Windows.Controls;
4 | using System.Windows.Documents;
5 | using System.Windows.Input;
6 | using System.Windows.Media;
7 | using System.Windows.Shapes;
8 | using CroppingImageLibrary.Services.State;
9 | using CroppingImageLibrary.Services.Tools;
10 |
11 | namespace CroppingImageLibrary.Services
12 | {
13 | public class CropArea
14 | {
15 | public readonly Size OriginalSize;
16 | public readonly Rect CroppedRectAbsolute;
17 |
18 | public CropArea(Size originalSize, Rect croppedRectAbsolute)
19 | {
20 | OriginalSize = originalSize;
21 | CroppedRectAbsolute = croppedRectAbsolute;
22 | }
23 | }
24 |
25 | public class CropService
26 | {
27 | private readonly CropAdorner _cropAdorner;
28 | private readonly Canvas _canvas;
29 | private readonly Tools.CropTool _cropTool;
30 |
31 | private IToolState _currentToolState;
32 | private readonly IToolState _createState;
33 | private readonly IToolState _dragState;
34 | private readonly IToolState _completeState;
35 |
36 | public Adorner Adorner => _cropAdorner;
37 |
38 | private enum TouchPoint
39 | {
40 | OutsideRectangle,
41 | InsideRectangle
42 | }
43 |
44 | public CropService(FrameworkElement adornedElement)
45 | {
46 | _canvas = new Canvas
47 | {
48 | Height = adornedElement.ActualHeight,
49 | Width = adornedElement.ActualWidth
50 | };
51 | _cropAdorner = new CropAdorner(adornedElement, _canvas);
52 | var adornerLayer = AdornerLayer.GetAdornerLayer(adornedElement);
53 | Debug.Assert(adornerLayer != null, nameof(adornerLayer) + " != null");
54 | adornerLayer.Add(_cropAdorner);
55 |
56 | var cropShape = new CropShape(
57 | new Rectangle
58 | {
59 | Height = 0,
60 | Width = 0,
61 | Stroke = Brushes.Black,
62 | StrokeThickness = 1.5
63 | },
64 | new Rectangle
65 | {
66 | Stroke = Brushes.White,
67 | StrokeDashArray = new DoubleCollection(new double[] { 4, 4 })
68 | }
69 | );
70 | _cropTool = new CropTool(_canvas);
71 | _createState = new CreateState(_cropTool, _canvas);
72 | _completeState = new CompleteState();
73 | _dragState = new DragState(_cropTool, _canvas);
74 | _currentToolState = _completeState;
75 |
76 | _cropAdorner.MouseLeftButtonDown += AdornerOnMouseLeftButtonDown;
77 | _cropAdorner.MouseMove += AdornerOnMouseMove;
78 | _cropAdorner.MouseLeftButtonUp += AdornerOnMouseLeftButtonUp;
79 |
80 | _cropTool.Redraw(0, 0, 0, 0);
81 | }
82 |
83 | public CropArea GetCroppedArea() =>
84 | new CropArea(
85 | _cropAdorner.RenderSize,
86 | new Rect(_cropTool.TopLeftX, _cropTool.TopLeftY, _cropTool.Width, _cropTool.Height)
87 | );
88 |
89 | private void AdornerOnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
90 | {
91 | _canvas.ReleaseMouseCapture();
92 | _currentToolState = _completeState;
93 | }
94 |
95 | private void AdornerOnMouseMove(object sender, MouseEventArgs e)
96 | {
97 | var point = e.GetPosition(_canvas);
98 | var newPosition = _currentToolState.OnMouseMove(point);
99 | if (newPosition.HasValue)
100 | {
101 | _cropTool.Redraw(newPosition.Value.Left, newPosition.Value.Top, newPosition.Value.Width, newPosition.Value.Height);
102 | }
103 |
104 | }
105 |
106 | private void AdornerOnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
107 | {
108 | _canvas.CaptureMouse();
109 | var point = e.GetPosition(_canvas);
110 | var touch = GetTouchPoint(point);
111 | if (touch == TouchPoint.OutsideRectangle)
112 | {
113 | _currentToolState = _createState;
114 | }
115 | else if (touch == TouchPoint.InsideRectangle)
116 | {
117 | _currentToolState = _dragState;
118 | }
119 | _currentToolState.OnMouseDown(point);
120 | }
121 |
122 | private TouchPoint GetTouchPoint(Point mousePoint)
123 | {
124 | //left
125 | if (mousePoint.X < _cropTool.TopLeftX)
126 | return TouchPoint.OutsideRectangle;
127 | //right
128 | if (mousePoint.X > _cropTool.BottomRightX)
129 | return TouchPoint.OutsideRectangle;
130 | //top
131 | if (mousePoint.Y < _cropTool.TopLeftY)
132 | return TouchPoint.OutsideRectangle;
133 | //bottom
134 | if (mousePoint.Y > _cropTool.BottomRightY)
135 | return TouchPoint.OutsideRectangle;
136 |
137 | return TouchPoint.InsideRectangle;
138 | }
139 | }
140 | }
141 |
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary/Services/State/CompleteState.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 |
3 | namespace CroppingImageLibrary.Services.State
4 | {
5 | internal class CompleteState : IToolState
6 | {
7 | public void OnMouseDown(Point point)
8 | {
9 | }
10 |
11 | public Position? OnMouseMove(Point point)
12 | {
13 | return null;
14 | }
15 |
16 | public void OnMouseUp(Point point)
17 | {
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary/Services/State/CreateState.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Windows;
3 | using System.Windows.Controls;
4 | using CroppingImageLibrary.Services.Tools;
5 |
6 | namespace CroppingImageLibrary.Services.State
7 | {
8 | internal class CreateState : IToolState
9 | {
10 | private readonly CropTool _cropTool;
11 | private readonly Canvas _canvas;
12 |
13 | private Point _startPoint;
14 |
15 | public CreateState(CropTool cropTool, Canvas canvas)
16 | {
17 | _cropTool = cropTool;
18 | _canvas = canvas;
19 | }
20 |
21 | public void OnMouseDown(Point point)
22 | {
23 | _startPoint = point;
24 | }
25 |
26 | public Position? OnMouseMove(Point point)
27 | {
28 | double left = Math.Min(point.X, _startPoint.X);
29 | double top = Math.Min(point.Y, _startPoint.Y);
30 | double width = Math.Abs(point.X - _startPoint.X);
31 | double height = Math.Abs(point.Y - _startPoint.Y);
32 |
33 | SetCreateBorderLimit(ref left, ref top, ref width, ref height);
34 |
35 | return new Position(left, top, width, height);
36 | }
37 |
38 | public void OnMouseUp(Point point)
39 | {
40 |
41 | }
42 |
43 | private void SetCreateBorderLimit(ref double newX, ref double newY, ref double newWidth, ref double newHeight)
44 | {
45 | // set drawing limits(canvas borders)
46 | // so we can't select area outside of canvas border
47 | //set top limit
48 | if (newY < 0)
49 | {
50 | newY = 0;
51 | newHeight = _cropTool.Height;
52 | }
53 |
54 | //set right limit
55 | if (newX + newWidth > _canvas.ActualWidth)
56 | {
57 | newWidth = _canvas.ActualWidth - newX;
58 | }
59 |
60 | //set left limit
61 | if (newX < 0)
62 | {
63 | newX = 0;
64 | newWidth = _cropTool.Width;
65 | }
66 |
67 | //set bottom limit
68 | if (newY + newHeight > _canvas.ActualHeight)
69 | {
70 | newHeight = _canvas.ActualHeight - newY;
71 | }
72 | }
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary/Services/State/DragState.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 | using System.Windows.Controls;
3 | using CroppingImageLibrary.Services.Tools;
4 |
5 | namespace CroppingImageLibrary.Services.State
6 | {
7 | internal class DragState : IToolState
8 | {
9 | private readonly CropTool _cropTool;
10 | private readonly Canvas _canvas;
11 | private Point _lastPoint;
12 |
13 | public DragState(CropTool cropTool, Canvas canvas)
14 | {
15 | _cropTool = cropTool;
16 | _canvas = canvas;
17 | }
18 |
19 | public void OnMouseDown(Point point)
20 | {
21 | _lastPoint = point;
22 | }
23 |
24 | public Position? OnMouseMove(Point point)
25 | {
26 | //see how much the mouse has moved
27 | double offsetX = point.X - _lastPoint.X;
28 | double offsetY = point.Y - _lastPoint.Y;
29 |
30 | //get the original rectangle parameters
31 | double left = _cropTool.TopLeftX;
32 | double top = _cropTool.TopLeftY;
33 |
34 | left += offsetX;
35 | top += offsetY;
36 |
37 |
38 | SetBorderLimit(ref left, ref top, ref offsetX, ref offsetY);
39 | _lastPoint = point;
40 | return new Position(left, top, _cropTool.Width, _cropTool.Height);
41 | }
42 |
43 | public void OnMouseUp(Point point)
44 | {
45 |
46 | }
47 |
48 | private void SetBorderLimit(ref double newX, ref double newY, ref double offsetX, ref double offsetY)
49 | {
50 | //set dragging limits(canvas borders)
51 | //set bottom limit
52 | if (newY + offsetY + _cropTool.Height > _canvas.ActualHeight)
53 | {
54 | newY = _canvas.ActualHeight - _cropTool.Height;
55 | }
56 |
57 | //set right limit
58 | if (newX + offsetX + _cropTool.Width > _canvas.ActualWidth)
59 | {
60 | newX = _canvas.ActualWidth - _cropTool.Width;
61 | }
62 |
63 | //set left limit
64 | if (newX < 0)
65 | {
66 | newX = 0;
67 | }
68 |
69 | //set top limit
70 | if (newY < 0)
71 | {
72 | newY = 0;
73 | }
74 | }
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary/Services/State/IToolState.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 |
3 | namespace CroppingImageLibrary.Services.State
4 | {
5 | internal interface IToolState
6 | {
7 | void OnMouseDown(Point point);
8 | Position? OnMouseMove(Point point);
9 | void OnMouseUp(Point point);
10 | }
11 | }
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary/Services/State/Position.cs:
--------------------------------------------------------------------------------
1 | namespace CroppingImageLibrary.Services.State
2 | {
3 | internal readonly struct Position
4 | {
5 | public double Left { get; }
6 | public double Top { get; }
7 | public double Width { get; }
8 | public double Height { get; }
9 |
10 | public Position(double left, double top, double width, double height)
11 | {
12 | Left = left;
13 | Top = top;
14 | Width = width;
15 | Height = height;
16 | }
17 | }
18 | }
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary/Services/Tools/CropShape.cs:
--------------------------------------------------------------------------------
1 | using System.Windows.Controls;
2 | using System.Windows.Shapes;
3 |
4 | namespace CroppingImageLibrary.Services.Tools
5 | {
6 | internal class CropShape
7 | {
8 | public Shape Shape { get; }
9 | public Shape DashedShape { get; }
10 |
11 | public CropShape(Shape shape, Shape dashedShape)
12 | {
13 | Shape = shape;
14 | DashedShape = dashedShape;
15 | }
16 |
17 | public void Redraw(double newX, double newY, double newWidth, double newHeight)
18 | {
19 | //dont use negative value
20 | if (newHeight >= 0 && newWidth >= 0)
21 | {
22 | RedrawSolidShape(newX, newY, newWidth, newHeight);
23 | RedrawDashedShape();
24 | }
25 | }
26 |
27 | private void RedrawSolidShape(double newX, double newY, double newWidth, double newHeight)
28 | {
29 | Canvas.SetLeft(Shape, newX);
30 | Canvas.SetTop(Shape, newY);
31 | Shape.Width = newWidth;
32 | Shape.Height = newHeight;
33 | }
34 |
35 | private void RedrawDashedShape()
36 | {
37 | DashedShape.Height = Shape.Height;
38 | DashedShape.Width = Shape.Width;
39 | Canvas.SetLeft(DashedShape, Canvas.GetLeft(Shape));
40 | Canvas.SetTop(DashedShape, Canvas.GetTop(Shape));
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary/Services/Tools/CropTool.cs:
--------------------------------------------------------------------------------
1 | using System.Windows.Controls;
2 | using System.Windows.Media;
3 | using System.Windows.Shapes;
4 |
5 | namespace CroppingImageLibrary.Services.Tools
6 | {
7 | internal class CropTool
8 | {
9 | private readonly Canvas _canvas;
10 | private readonly CropShape _cropShape;
11 | private readonly ShadeTool _shadeService;
12 | private readonly ThumbTool _thumbService;
13 | private readonly TextTool _textService;
14 |
15 | public double TopLeftX => Canvas.GetLeft(_cropShape.Shape);
16 | public double TopLeftY => Canvas.GetTop(_cropShape.Shape);
17 | public double BottomRightX => Canvas.GetLeft(_cropShape.Shape) + _cropShape.Shape.Width;
18 | public double BottomRightY => Canvas.GetTop(_cropShape.Shape) + _cropShape.Shape.Height;
19 | public double Height => _cropShape.Shape.Height;
20 | public double Width => _cropShape.Shape.Width;
21 |
22 | public CropTool(Canvas canvas)
23 | {
24 | _canvas = canvas;
25 | _cropShape = new CropShape(new Rectangle {
26 | Height = 0,
27 | Width = 0,
28 | Stroke = Brushes.Black,
29 | StrokeThickness = 1.5
30 | },
31 | new Rectangle {
32 | Stroke = Brushes.White,
33 | StrokeDashArray = new DoubleCollection(new double[] { 4, 4 })
34 | });
35 |
36 | _shadeService = new ShadeTool(canvas, this);
37 | _thumbService = new ThumbTool(canvas, this);
38 | _textService = new TextTool(this);
39 |
40 | _canvas.Children.Add(_cropShape.Shape);
41 | _canvas.Children.Add(_cropShape.DashedShape);
42 |
43 |
44 | _canvas.Children.Add(_shadeService.ShadeOverlay);
45 |
46 | _canvas.Children.Add(_thumbService.BottomMiddle);
47 | _canvas.Children.Add(_thumbService.LeftMiddle);
48 | _canvas.Children.Add(_thumbService.TopMiddle);
49 | _canvas.Children.Add(_thumbService.RightMiddle);
50 | _canvas.Children.Add(_thumbService.TopLeft);
51 | _canvas.Children.Add(_thumbService.TopRight);
52 | _canvas.Children.Add(_thumbService.BottomLeft);
53 | _canvas.Children.Add(_thumbService.BottomRight);
54 |
55 | _canvas.Children.Add(_textService.TextBlock);
56 | }
57 |
58 | public void Redraw(double newX, double newY, double newWidth, double newHeight)
59 | {
60 | _cropShape.Redraw(newX, newY, newWidth, newHeight);
61 | _shadeService.Redraw();
62 | _thumbService.Redraw();
63 | _textService.Redraw();
64 | }
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary/Services/Tools/ShadeTool.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 | using System.Windows.Controls;
3 | using System.Windows.Media;
4 | using System.Windows.Shapes;
5 |
6 | namespace CroppingImageLibrary.Services.Tools
7 | {
8 | internal class ShadeTool
9 | {
10 | private readonly CropTool _cropTool;
11 | private readonly RectangleGeometry _rectangleGeo;
12 |
13 | public Path ShadeOverlay { get; set; }
14 |
15 | public ShadeTool(Canvas canvas, CropTool cropTool)
16 | {
17 | _cropTool = cropTool;
18 |
19 | ShadeOverlay = new Path
20 | {
21 | Fill = Brushes.Black,
22 | Opacity = 0.5
23 | };
24 |
25 | var geometryGroup = new GeometryGroup();
26 | RectangleGeometry geometry1 =
27 | new RectangleGeometry(new Rect(new Size(canvas.Width, canvas.Height)));
28 | _rectangleGeo = new RectangleGeometry(
29 | new Rect(
30 | _cropTool.TopLeftX,
31 | _cropTool.TopLeftY,
32 | _cropTool.Width,
33 | _cropTool.Height
34 | )
35 | );
36 | geometryGroup.Children.Add(geometry1);
37 | geometryGroup.Children.Add(_rectangleGeo);
38 | ShadeOverlay.Data = geometryGroup;
39 | }
40 |
41 | public void Redraw()
42 | {
43 | _rectangleGeo.Rect = new Rect(
44 | _cropTool.TopLeftX,
45 | _cropTool.TopLeftY,
46 | _cropTool.Width,
47 | _cropTool.Height
48 | );
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary/Services/Tools/TextTool.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 | using System.Windows.Controls;
3 | using System.Windows.Media;
4 |
5 | namespace CroppingImageLibrary.Services.Tools
6 | {
7 | internal class TextTool
8 | {
9 | const double OffsetTop = 2;
10 | const double OffsetLeft = 5;
11 |
12 | public TextBlock TextBlock { get; }
13 | private readonly CropTool _cropTool;
14 |
15 | public TextTool(CropTool cropTool)
16 | {
17 | _cropTool = cropTool;
18 | TextBlock = new TextBlock
19 | {
20 | Text = "Size counter",
21 | FontSize = 14,
22 | Foreground = Brushes.White,
23 | Background = Brushes.Black,
24 | Visibility = Visibility.Hidden
25 | };
26 | }
27 |
28 |
29 | ///
30 | /// Manage visibility of text
31 | ///
32 | /// Set current visibility
33 | public void ShowText(bool isVisible)
34 | {
35 | TextBlock.Visibility = isVisible ? Visibility.Visible : Visibility.Hidden;
36 | }
37 |
38 | ///
39 | /// Update (redraw) text label
40 | ///
41 | public void Redraw()
42 | {
43 | if (_cropTool.Height <= 0 && _cropTool.Width <= 0)
44 | ShowText(false);
45 | else
46 | ShowText(true);
47 |
48 | double calculateTop = _cropTool.TopLeftY - TextBlock.ActualHeight - OffsetTop;
49 | if (calculateTop < 0)
50 | calculateTop = OffsetTop;
51 |
52 | Canvas.SetLeft(TextBlock, _cropTool.TopLeftX + OffsetLeft);
53 | Canvas.SetTop(TextBlock, calculateTop);
54 | TextBlock.Text = $"w: {_cropTool.Width}, h: {_cropTool.Height}";
55 | }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/CroppingImageLibrary/Services/Tools/ThumbTool.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 | using System.Windows.Controls;
3 | using System.Windows.Controls.Primitives;
4 | using System.Windows.Input;
5 | using System.Windows.Media;
6 |
7 | namespace CroppingImageLibrary.Services.Tools
8 | {
9 | internal class ThumbCrop : Thumb
10 | {
11 | public ThumbCrop(double thumbSize, Cursor cursor)
12 | {
13 | ThumbSize = thumbSize;
14 | Cursor = cursor;
15 | PreviewMouseLeftButtonDown += ThumbCrop_PreviewMouseLeftButtonDown;
16 | PreviewMouseLeftButtonUp += ThumbCrop_PreviewMouseLeftButtonUp;
17 | }
18 |
19 | private void ThumbCrop_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
20 | {
21 | ThumbCrop thumb = sender as ThumbCrop;
22 | thumb?.ReleaseMouseCapture();
23 | }
24 |
25 | private void ThumbCrop_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
26 | {
27 | ThumbCrop thumb = sender as ThumbCrop;
28 | thumb?.CaptureMouse();
29 | }
30 |
31 | public double ThumbSize { get; }
32 |
33 | ///
34 | /// Set thumb to corresponding positions
35 | ///
36 | /// X coordinate
37 | /// Y coordinate
38 | public void Redraw(double x, double y)
39 | {
40 | Canvas.SetTop(this, y - ThumbSize / 2);
41 | Canvas.SetLeft(this, x - ThumbSize / 2);
42 | }
43 |
44 | protected override Visual GetVisualChild(int index) => null;
45 |
46 | ///
47 | /// Custom visual style of thumb
48 | ///
49 | ///
50 | protected override void OnRender(DrawingContext drawingContext)
51 | {
52 | drawingContext.DrawRectangle(Brushes.White, new Pen(Brushes.Black, 2), new Rect(new Size(ThumbSize, ThumbSize)));
53 | drawingContext.DrawRectangle(Brushes.Black, new Pen(Brushes.Black, 0), new Rect(2, 2, 6, 6));
54 | }
55 | }
56 | internal class ThumbTool
57 | {
58 | private readonly CropTool _cropTool;
59 |
60 | public ThumbCrop BottomMiddle { get; }
61 | public ThumbCrop LeftMiddle { get; }
62 | public ThumbCrop TopMiddle { get; }
63 | public ThumbCrop RightMiddle { get; }
64 | public ThumbCrop TopLeft { get; }
65 | public ThumbCrop TopRight { get; }
66 | public ThumbCrop BottomLeft { get; }
67 | public ThumbCrop BottomRight { get; }
68 | private readonly Canvas _canvas;
69 | private readonly double _thumbSize = 10;
70 |
71 | public ThumbTool(Canvas canvas, CropTool cropTool)
72 | {
73 | _canvas = canvas;
74 | _cropTool = cropTool;
75 | BottomMiddle = new ThumbCrop(_thumbSize, Cursors.SizeNS);
76 | LeftMiddle = new ThumbCrop(_thumbSize, Cursors.SizeWE);
77 | TopMiddle = new ThumbCrop(_thumbSize, Cursors.SizeNS);
78 | RightMiddle = new ThumbCrop(_thumbSize, Cursors.SizeWE);
79 | TopLeft = new ThumbCrop(_thumbSize, Cursors.SizeNWSE);
80 | TopRight = new ThumbCrop(_thumbSize, Cursors.SizeNESW);
81 | BottomLeft = new ThumbCrop(_thumbSize, Cursors.SizeNESW);
82 | BottomRight = new ThumbCrop(_thumbSize, Cursors.SizeNWSE);
83 |
84 | LeftMiddle.DragDelta += LeftMiddle_DragDelta;
85 | BottomMiddle.DragDelta += BottomMiddle_DragDelta;
86 | TopMiddle.DragDelta += TopMiddle_DragDelta;
87 | RightMiddle.DragDelta += RightMiddle_DragDelta;
88 | TopLeft.DragDelta += TopLeft_DragDelta;
89 | TopRight.DragDelta += TopRight_DragDelta;
90 | BottomLeft.DragDelta += BottomLeft_DragDelta;
91 | BottomRight.DragDelta += BottomRight_DragDelta;
92 | }
93 |
94 | private void BottomRight_DragDelta(object sender, DragDeltaEventArgs e)
95 | {
96 | ThumbCrop thumb = sender as ThumbCrop;
97 |
98 | double resultThumbLeft = Canvas.GetLeft(thumb) + e.HorizontalChange;
99 |
100 | if (resultThumbLeft > _canvas.ActualWidth)
101 | resultThumbLeft = _canvas.ActualWidth;
102 |
103 | double thumbResultTop = Canvas.GetTop(thumb) + e.VerticalChange;
104 | if (thumbResultTop + _thumbSize / 2 > _canvas.ActualHeight)
105 | thumbResultTop = _canvas.ActualHeight - _thumbSize / 2;
106 |
107 | double resultHeight = thumbResultTop - _cropTool.TopLeftY + _thumbSize / 2;
108 | double resultWidth = resultThumbLeft - _cropTool.TopLeftX;
109 |
110 | _cropTool.Redraw(_cropTool.TopLeftX, _cropTool.TopLeftY, resultWidth, resultHeight);
111 | }
112 |
113 | private void BottomLeft_DragDelta(object sender, DragDeltaEventArgs e)
114 | {
115 | ThumbCrop thumb = sender as ThumbCrop;
116 |
117 | double thumbResultTop = Canvas.GetTop(thumb) + e.VerticalChange;
118 | if (thumbResultTop + _thumbSize / 2 > _canvas.ActualHeight)
119 | thumbResultTop = _canvas.ActualHeight - _thumbSize / 2;
120 |
121 | double resultHeight = thumbResultTop - _cropTool.TopLeftY + _thumbSize / 2;
122 |
123 | double resultThumbLeft = Canvas.GetLeft(thumb) + e.HorizontalChange;
124 | if (resultThumbLeft < 0)
125 | resultThumbLeft = -_thumbSize / 2;
126 |
127 | double offset = Canvas.GetLeft(thumb) - resultThumbLeft;
128 | double resultLeft = resultThumbLeft + _thumbSize / 2;
129 | double resultWidth = _cropTool.Width + offset;
130 | _cropTool.Redraw(resultLeft, _cropTool.TopLeftY, resultWidth, resultHeight);
131 | }
132 |
133 | private void TopRight_DragDelta(object sender, DragDeltaEventArgs e)
134 | {
135 | ThumbCrop thumb = sender as ThumbCrop;
136 | double newTop = Canvas.GetTop(thumb) + e.VerticalChange;
137 | double newLeft = Canvas.GetLeft(thumb) + e.HorizontalChange;
138 |
139 | if (newTop < 0)
140 | newTop = -_thumbSize / 2;
141 |
142 | double offset = Canvas.GetTop(thumb) - newTop;
143 | double resultHeight = _cropTool.Height + offset;
144 | double resultTop = newTop + _thumbSize / 2;
145 |
146 |
147 |
148 | if (newLeft > _canvas.ActualWidth)
149 | newLeft = _canvas.ActualWidth;
150 |
151 | double resultWidth = newLeft - _cropTool.TopLeftX;
152 | _cropTool.Redraw(_cropTool.TopLeftX, resultTop, resultWidth, resultHeight);
153 | }
154 |
155 | private void TopLeft_DragDelta(object sender, DragDeltaEventArgs e)
156 | {
157 | ThumbCrop thumb = sender as ThumbCrop;
158 | double newTop = Canvas.GetTop(thumb) + e.VerticalChange;
159 | double newLeft = Canvas.GetLeft(thumb) + e.HorizontalChange;
160 |
161 | if (newTop < 0)
162 | newTop = -_thumbSize / 2;
163 | if (newLeft < 0)
164 | newLeft = -_thumbSize / 2;
165 |
166 | double offsetTop = Canvas.GetTop(thumb) - newTop;
167 | double resultHeight = _cropTool.Height + offsetTop;
168 | double resultTop = newTop + _thumbSize / 2;
169 |
170 | double offsetLeft = Canvas.GetLeft(thumb) - newLeft;
171 | double resultLeft = newLeft + _thumbSize / 2;
172 | double resultWidth = _cropTool.Width + offsetLeft;
173 |
174 | _cropTool.Redraw(resultLeft, resultTop, resultWidth, resultHeight);
175 | }
176 |
177 | private void RightMiddle_DragDelta(object sender, DragDeltaEventArgs e)
178 | {
179 | ThumbCrop thumb = sender as ThumbCrop;
180 | double resultThumbLeft = Canvas.GetLeft(thumb) + e.HorizontalChange;
181 |
182 | if (resultThumbLeft > _canvas.ActualWidth)
183 | resultThumbLeft = _canvas.ActualWidth;
184 |
185 | double resultWidth = resultThumbLeft - _cropTool.TopLeftX;
186 | _cropTool.Redraw(_cropTool.TopLeftX, _cropTool.TopLeftY, resultWidth, _cropTool.Height);
187 | }
188 |
189 | private void TopMiddle_DragDelta(object sender, DragDeltaEventArgs e)
190 | {
191 | ThumbCrop thumb = sender as ThumbCrop;
192 | double resultThumbTop = Canvas.GetTop(thumb) + e.VerticalChange;
193 |
194 | if (resultThumbTop < 0)
195 | resultThumbTop = -_thumbSize / 2;
196 |
197 | double offset = Canvas.GetTop(thumb) - resultThumbTop;
198 | double resultHeight = _cropTool.Height + offset;
199 | double resultTop = resultThumbTop + _thumbSize / 2;
200 | _cropTool.Redraw(_cropTool.TopLeftX, resultTop, _cropTool.Width, resultHeight);
201 | }
202 |
203 | private void LeftMiddle_DragDelta(object sender, DragDeltaEventArgs e)
204 | {
205 | ThumbCrop thumb = sender as ThumbCrop;
206 | double resultThumbLeft = Canvas.GetLeft(thumb) + e.HorizontalChange;
207 |
208 | if (resultThumbLeft < 0)
209 | resultThumbLeft = -_thumbSize / 2;
210 |
211 | double offset = Canvas.GetLeft(thumb) - resultThumbLeft;
212 | double resultLeft = resultThumbLeft + _thumbSize / 2;
213 | double resultWidth = _cropTool.Width + offset;
214 | _cropTool.Redraw(resultLeft, _cropTool.TopLeftY, resultWidth, _cropTool.Height);
215 | }
216 |
217 | private void BottomMiddle_DragDelta(object sender, DragDeltaEventArgs e)
218 | {
219 | ThumbCrop thumb = sender as ThumbCrop;
220 | double thumbResultTop = Canvas.GetTop(thumb) + e.VerticalChange;
221 |
222 | if (thumbResultTop > _canvas.ActualHeight)
223 | thumbResultTop = _canvas.ActualHeight;
224 |
225 | _cropTool.Redraw(_cropTool.TopLeftX, _cropTool.TopLeftY, _cropTool.Width, thumbResultTop - _cropTool.TopLeftY);
226 | }
227 |
228 |
229 | public void Redraw()
230 | {
231 | if (_cropTool.Height <= 0 && _cropTool.Width <= 0)
232 | {
233 | ShowThumbs(false);
234 | return;
235 | }
236 |
237 | BottomMiddle.Redraw(_cropTool.TopLeftX + _cropTool.Width / 2, _cropTool.TopLeftY + _cropTool.Height);
238 | LeftMiddle.Redraw(_cropTool.TopLeftX, _cropTool.TopLeftY + _cropTool.Height / 2);
239 | TopMiddle.Redraw(_cropTool.TopLeftX + _cropTool.Width / 2, _cropTool.TopLeftY);
240 | RightMiddle.Redraw(_cropTool.TopLeftX + _cropTool.Width, _cropTool.TopLeftY + _cropTool.Height / 2);
241 | TopLeft.Redraw(_cropTool.TopLeftX, _cropTool.TopLeftY);
242 | TopRight.Redraw(_cropTool.TopLeftX + _cropTool.Width, _cropTool.TopLeftY);
243 | BottomLeft.Redraw(_cropTool.TopLeftX, _cropTool.TopLeftY + _cropTool.Height);
244 | BottomRight.Redraw(_cropTool.TopLeftX + _cropTool.Width, _cropTool.TopLeftY + _cropTool.Height);
245 | ShowThumbs(true);
246 | }
247 |
248 | private void ShowThumbs(bool isVisible)
249 | {
250 | if (_cropTool.Height > 0 && _cropTool.Width > 0)
251 | {
252 | BottomMiddle.Visibility = Visibility.Visible;
253 | LeftMiddle.Visibility = Visibility.Visible;
254 | TopMiddle.Visibility = Visibility.Visible;
255 | RightMiddle.Visibility = Visibility.Visible;
256 | TopLeft.Visibility = Visibility.Visible;
257 | TopRight.Visibility = Visibility.Visible;
258 | BottomLeft.Visibility = Visibility.Visible;
259 | BottomRight.Visibility = Visibility.Visible;
260 | }
261 | else
262 | {
263 | BottomMiddle.Visibility = Visibility.Hidden;
264 | LeftMiddle.Visibility = Visibility.Hidden;
265 | TopMiddle.Visibility = Visibility.Hidden;
266 | RightMiddle.Visibility = Visibility.Hidden;
267 | TopLeft.Visibility = Visibility.Hidden;
268 | TopRight.Visibility = Visibility.Hidden;
269 | BottomLeft.Visibility = Visibility.Hidden;
270 | BottomRight.Visibility = Visibility.Hidden;
271 | }
272 | }
273 | }
274 | }
275 |
--------------------------------------------------------------------------------
/UI-Cropping-Image-Library/UI-Cropping-Image-Library.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.27004.2009
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CroppingImageLibrary", "CroppingImageLibrary\CroppingImageLibrary.csproj", "{AADA3516-FF2A-4C8D-AC3F-43C38ACB7BE4}"
7 | EndProject
8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CroppingImageLibrary.SampleApp", "CroppingImageLibrary.SampleApp\CroppingImageLibrary.SampleApp.csproj", "{65C9DD8D-8B24-4EC1-A2B5-88FF42F46D01}"
9 | EndProject
10 | Global
11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
12 | Debug|Any CPU = Debug|Any CPU
13 | Release|Any CPU = Release|Any CPU
14 | EndGlobalSection
15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
16 | {AADA3516-FF2A-4C8D-AC3F-43C38ACB7BE4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
17 | {AADA3516-FF2A-4C8D-AC3F-43C38ACB7BE4}.Debug|Any CPU.Build.0 = Debug|Any CPU
18 | {AADA3516-FF2A-4C8D-AC3F-43C38ACB7BE4}.Release|Any CPU.ActiveCfg = Release|Any CPU
19 | {AADA3516-FF2A-4C8D-AC3F-43C38ACB7BE4}.Release|Any CPU.Build.0 = Release|Any CPU
20 | {65C9DD8D-8B24-4EC1-A2B5-88FF42F46D01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21 | {65C9DD8D-8B24-4EC1-A2B5-88FF42F46D01}.Debug|Any CPU.Build.0 = Debug|Any CPU
22 | {65C9DD8D-8B24-4EC1-A2B5-88FF42F46D01}.Release|Any CPU.ActiveCfg = Release|Any CPU
23 | {65C9DD8D-8B24-4EC1-A2B5-88FF42F46D01}.Release|Any CPU.Build.0 = Release|Any CPU
24 | EndGlobalSection
25 | GlobalSection(SolutionProperties) = preSolution
26 | HideSolutionNode = FALSE
27 | EndGlobalSection
28 | GlobalSection(ExtensibilityGlobals) = postSolution
29 | SolutionGuid = {058BB281-92D3-419C-B611-A4C4CAB4BF2F}
30 | EndGlobalSection
31 | EndGlobal
32 |
--------------------------------------------------------------------------------
/cropped-demo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dmitryshelamov/UI-Cropping-Image/ed3046f401be619ab10b43779f1e14b0397c560c/cropped-demo.png
--------------------------------------------------------------------------------
/cropped-result-info.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dmitryshelamov/UI-Cropping-Image/ed3046f401be619ab10b43779f1e14b0397c560c/cropped-result-info.png
--------------------------------------------------------------------------------
/cropped-result.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dmitryshelamov/UI-Cropping-Image/ed3046f401be619ab10b43779f1e14b0397c560c/cropped-result.png
--------------------------------------------------------------------------------