Rotatebox.xaml.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Windows;
  5. using System.Windows.Controls;
  6. using System.Windows.Data;
  7. using System.Windows.Documents;
  8. using System.Windows.Input;
  9. using System.Windows.Media;
  10. using System.Windows.Media.Imaging;
  11. using System.Windows.Navigation;
  12. using System.Windows.Shapes;
  13. namespace PixiEditor.Views
  14. {
  15. /// <summary>
  16. /// Interaction logic for Rotatebox.xaml
  17. /// </summary>
  18. public partial class Rotatebox : UserControl
  19. {
  20. private double _height = 0, _width = 0;
  21. private float _offset = 90;
  22. public Rotatebox()
  23. {
  24. InitializeComponent();
  25. MouseLeftButtonDown += OnMouseLeftButtonDown;
  26. MouseUp += OnMouseUp;
  27. MouseMove += OnMouseMove;
  28. }
  29. // Using a DependencyProperty backing store for Angle.
  30. public static readonly DependencyProperty AngleProperty =
  31. DependencyProperty.Register("Angle", typeof(double), typeof(Rotatebox), new UIPropertyMetadata(0.0));
  32. public double Angle
  33. {
  34. get { return (double)GetValue(AngleProperty); }
  35. set { SetValue(AngleProperty, value); }
  36. }
  37. private void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
  38. {
  39. Mouse.Capture(this);
  40. _width = ActualWidth;
  41. _height = ActualHeight;
  42. }
  43. private void OnMouseUp(object sender, MouseButtonEventArgs e)
  44. {
  45. Mouse.Capture(null);
  46. }
  47. private void OnMouseMove(object sender, MouseEventArgs e)
  48. {
  49. if (Equals(Mouse.Captured, this))
  50. {
  51. // Get the current mouse position relative to the control
  52. Point currentLocation = Mouse.GetPosition(this);
  53. // We want to rotate around the center of the knob, not the top corner
  54. Point knobCenter = new Point(_width / 2, _height/ 2);
  55. // Calculate an angle
  56. double radians = Math.Atan((currentLocation.Y - knobCenter.Y) /
  57. (currentLocation.X - knobCenter.X));
  58. Angle = radians * 180 / Math.PI + _offset;
  59. // Apply a 180 degree shift when X is negative so that we can rotate
  60. // all of the way around
  61. if (currentLocation.X - knobCenter.X < 0)
  62. {
  63. Angle += 180;
  64. }
  65. }
  66. }
  67. }
  68. }