画矩形

代码

  1. public partial class MainWindow : Window
  2. {
  3. static Point startPoint;
  4. static Point endPoint;
  5. public MainWindow()
  6. {
  7. InitializeComponent();
  8. this.MouseLeftButtonDown += MainWindow_MouseLeftButtonDown;
  9. this.MouseMove += MainWindow_MouseMove;
  10. }
  11. private void MainWindow_MouseMove(object sender, MouseEventArgs e)
  12. {
  13. if (e.LeftButton == MouseButtonState.Pressed)
  14. {
  15. endPoint = e.GetPosition(sender as Window);
  16. DrawRectangle(sender);
  17. }
  18. }
  19. private void MainWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
  20. {
  21. var win = sender as Window;
  22. startPoint = e.GetPosition(win);
  23. }
  24. static void DrawRectangle(object sender)
  25. {
  26. var tmpPoint = startPoint;
  27. if (endPoint.X < startPoint.X)
  28. {
  29. startPoint.X = endPoint.X;
  30. endPoint.X = tmpPoint.X;
  31. }
  32. if (endPoint.Y < startPoint.Y)
  33. {
  34. startPoint.Y = endPoint.Y;
  35. endPoint.Y = tmpPoint.Y;
  36. }
  37. var win = sender as Window;
  38. var rect = new Rectangle();
  39. rect.Stroke = Brushes.Black;
  40. rect.Fill = Brushes.SkyBlue;
  41. rect.HorizontalAlignment = HorizontalAlignment.Left;
  42. rect.VerticalAlignment = VerticalAlignment.Center;
  43. rect.Height = Math.Abs(endPoint.Y - startPoint.Y);
  44. rect.Width = Math.Abs(endPoint.X - startPoint.X);
  45. Canvas canvas = new Canvas();
  46. Canvas.SetLeft(rect, startPoint.X);
  47. Canvas.SetTop(rect, startPoint.Y);
  48. canvas.Children.Add(rect);
  49. win.Content = canvas;
  50. }

效果

rectangle sample.gif