using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfApp22 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { Canvas cvs; Point leftTopPt; Point rightDownPt; Shape currentShape; Rectangle rect; bool isDrawing = false; public MainWindow() { WindowState = WindowState.Maximized; InitializeComponent(); Loaded += delegate { InitCvs(); }; } private void InitCvs() { cvs = new Canvas(); cvs.Width = this.ActualWidth; cvs.Height = this.ActualHeight; cvs.Background = new SolidColorBrush(Colors.White); cvs.MouseDown += Cvs_MouseDown; cvs.MouseMove += Cvs_MouseMove; cvs.MouseUp += Cvs_MouseUp; this.Content = cvs; } private void Cvs_MouseUp(object sender, MouseButtonEventArgs e) { if (isDrawing) { rightDownPt = e.GetPosition(cvs); DrawRectangle(); isDrawing = false; cvs.ReleaseMouseCapture(); } } private void Cvs_MouseMove(object sender, MouseEventArgs e) { } private void Cvs_MouseDown(object sender, MouseButtonEventArgs e) { if (!isDrawing) { leftTopPt = e.GetPosition(cvs); isDrawing = true; } else if (isDrawing) { rightDownPt = e.GetPosition(cvs); } cvs.CaptureMouse(); } private void DrawRectangle() { rect = new Rectangle(); rect.Width = rightDownPt.X - leftTopPt.X; rect.Height = rightDownPt.Y - leftTopPt.Y; rect.Fill = new SolidColorBrush(Colors.Red); rect.Stroke = new SolidColorBrush(Colors.Black); rect.StrokeThickness = 5; Canvas.SetLeft(rect, leftTopPt.X); Canvas.SetTop(rect, leftTopPt.Y); cvs.Children.Add(rect); this.Content = cvs; } } }
标签:draw,Windows,System,cvs,Cvs,using,wpf,mouse,rect From: https://www.cnblogs.com/Fred1987/p/18101979