wpf 鼠标操作画圆形
时间: 2023-09-03 15:08:43 浏览: 153
你可以使用WPF中的Canvas控件和鼠标事件来实现鼠标操作画圆形的功能。以下是一个简单的示例代码:
```xaml
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Canvas x:Name="canvas" Background="White" MouseDown="Canvas_MouseDown" MouseMove="Canvas_MouseMove" MouseUp="Canvas_MouseUp"/>
</Grid>
</Window>
```
```csharp
private bool isDrawing = false;
private Point startPoint;
private Ellipse ellipse;
private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
startPoint = e.GetPosition(canvas);
ellipse = new Ellipse
{
Stroke = Brushes.Black,
StrokeThickness = 1
};
Canvas.SetLeft(ellipse, startPoint.X);
Canvas.SetTop(ellipse, startPoint.Y);
canvas.Children.Add(ellipse);
isDrawing = true;
}
private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
if (isDrawing)
{
double x = Math.Min(e.GetPosition(canvas).X, startPoint.X);
double y = Math.Min(e.GetPosition(canvas).Y, startPoint.Y);
double width = Math.Abs(e.GetPosition(canvas).X - startPoint.X);
double height = Math.Abs(e.GetPosition(canvas).Y - startPoint.Y);
ellipse.Width = width;
ellipse.Height = height;
Canvas.SetLeft(ellipse, x);
Canvas.SetTop(ellipse, y);
}
}
private void Canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
isDrawing = false;
}
```
在这个例子中,我们在Canvas上添加了MouseDown、MouseMove和MouseUp事件的处理程序。当鼠标按下时,我们记录起始点并创建一个新的Ellipse对象。在MouseMove事件中,我们根据鼠标的位置调整Ellipse的大小和位置。当鼠标松开时,绘制过程结束。
阅读全文