WPF鼠标怎么绘制正方形
时间: 2024-10-10 16:03:05 浏览: 30
C#图形学绘制正方形
3星 · 编辑精心推荐
在Windows Presentation Foundation (WPF)中,你可以使用`System.Windows.Shapes`命名空间下的`Rectangle`控件来绘制正方形。以下是简单的步骤:
1. 首先,在XAML文件中添加一个`Canvas`元素作为绘图区域,这是放置图形的位置:
```xml
<Canvas x:Name="DrawingCanvas" Width="500" Height="500">
</Canvas>
```
2. 然后,在`.xaml.cs`或`.cs`背后的相关代码文件中,获取对`Canvas`的引用,并创建一个`Rectangle`实例:
```csharp
private void Initialize()
{
var square = new Rectangle();
}
```
3. 设置`Rectangle`的填充颜色和边框样式:
```csharp
square.Fill = Brushes.Red; // 或者其他颜色
square Stroke = Brushes.Black;
square.StrokeThickness = 2; // 边框宽度
```
4. 设置正方形的大小和位置。如果你想要一个边长固定的正方形,可以直接设置`Width`和`Height`属性为相同的值。例如:
```csharp
square.Width = square.Height = 100; // 如果边长为100像素
```
如果你想通过鼠标拖动来绘制,可以监听鼠标按下、移动和释放事件,并更新`Rectangle`的位置:
```csharp
canvas.MouseDown += Canvas_MouseDown;
canvas.MouseMove += Canvas_MouseMove;
canvas MouseUp += Canvas_MouseUp;
private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
startPoint = e.GetPosition(DrawingCanvas);
}
private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
if (!e.LeftButton.IsNullOrDefault())
{
endPoint = e.GetPosition(DrawingCanvas);
square.Width = Math.Abs(endPoint.X - startPoint.X);
square.Height = Math.Abs(endPoint.Y - startPoint.Y);
square.RenderTransformOrigin = new Point(0.5, 0.5); // 中心点缩放
Canvas.SetLeft(square, startPoint.X);
Canvas.SetTop(square, startPoint.Y);
}
}
private void Canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
startPoint = null;
}
```
现在,当你在`Canvas`上点击并拖动鼠标,就能看到一个红色的正方形了。
阅读全文