技术要点:
1.Canvas控件布局用到的Canvas.TopProperty以及Canvas.LeftProperty属性
2.MouseLeftButtonDown,MouseMove,MouseLeftButtonUp方法处理程序的调用
VB.NET代码如下:
Private isAddMouseEvent As Boolean = False
Private rectangle As Rectangle
Private point As Point
Private Sub btnMain_Click(ByVal sender As System.Object,ByVal e As System.Windows.RoutedEventArgs) Handles btnMain.Click
If Not isAddMouseEvent Then
AddHandler canvasMain.MouseLeftButtonDown,AddressOf MouseEventDown
isAddMouseEvent = True
Me.btnMain.IsEnabled = False
End If
End Sub
Private Sub MouseEventDown(ByVal sender As Object,ByVal e As MouseEventArgs)
rectangle = New Rectangle()
point = e.GetPosition(canvasMain)
rectangle.SetValue(Canvas.LeftProperty,point.X)
rectangle.SetValue(Canvas.TopProperty,point.Y)
rectangle.Opacity = 1
rectangle.Fill = New SolidColorBrush(Colors.Blue)
rectangle.RadiusX = 10
rectangle.RadiusY = 10
AddHandler canvasMain.MouseMove,AddressOf MouseMove
AddHandler canvasMain.MouseLeftButtonUp,AddressOf MouseUp
canvasMain.Children.Add(rectangle)
End Sub
Private Sub MouseMove(ByVal sender As Object,ByVal e As MouseEventArgs)
Dim tempPorint = e.GetPosition(canvasMain)
If tempPorint.X > point.X Then
rectangle.Width = tempPorint.X - point.X
End If
If tempPorint.X <= point.X Then
rectangle.SetValue(Canvas.LeftProperty,tempPorint.X)
rectangle.Width = point.X - tempPorint.X
End If
If tempPorint.Y > point.Y Then
rectangle.Height = tempPorint.Y - point.Y
End If
If tempPorint.Y <= point.Y Then
rectangle.Height = point.Y - tempPorint.Y
rectangle.SetValue(Canvas.TopProperty,tempPorint.Y)
End If
End Sub
Private Sub MouseUp(ByVal sender As Object,ByVal e As MouseEventArgs)
RemoveHandler canvasMain.MouseLeftButtonUp,AddressOf MouseUp
RemoveHandler canvasMain.MouseMove,AddressOf MouseMove
RemoveHandler canvasMain.MouseLeftButtonDown,AddressOf MouseEventDown
isAddMouseEvent = False
btnMain.IsEnabled = True
End Sub
<Grid x:Name="LayoutRoot" Background="White"> <Canvas x:Name="canvasMain" Width="1000" Height="1000" Background="Black" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> </Canvas> <Button x:Name="btnMain" Width="90" Height="28" Content="点我开始绘制矩形" Margin="0 0 0 0" VerticalAlignment="Top" HorizontalAlignment="Left"> </Button> </Grid>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。