画矩形
代码
public partial class MainWindow : Window
{
static Point startPoint;
static Point endPoint;
public MainWindow()
{
InitializeComponent();
this.MouseLeftButtonDown += MainWindow_MouseLeftButtonDown;
this.MouseMove += MainWindow_MouseMove;
}
private void MainWindow_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
endPoint = e.GetPosition(sender as Window);
DrawRectangle(sender);
}
}
private void MainWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var win = sender as Window;
startPoint = e.GetPosition(win);
}
static void DrawRectangle(object sender)
{
var tmpPoint = startPoint;
if (endPoint.X < startPoint.X)
{
startPoint.X = endPoint.X;
endPoint.X = tmpPoint.X;
}
if (endPoint.Y < startPoint.Y)
{
startPoint.Y = endPoint.Y;
endPoint.Y = tmpPoint.Y;
}
var win = sender as Window;
var rect = new Rectangle();
rect.Stroke = Brushes.Black;
rect.Fill = Brushes.SkyBlue;
rect.HorizontalAlignment = HorizontalAlignment.Left;
rect.VerticalAlignment = VerticalAlignment.Center;
rect.Height = Math.Abs(endPoint.Y - startPoint.Y);
rect.Width = Math.Abs(endPoint.X - startPoint.X);
Canvas canvas = new Canvas();
Canvas.SetLeft(rect, startPoint.X);
Canvas.SetTop(rect, startPoint.Y);
canvas.Children.Add(rect);
win.Content = canvas;
}
效果