Silverlight鼠标绘制矩形

来源:互联网 时间:1970-01-01

技术要点:

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>

本文来自softkexin的博客,原文地址:http://blog.csdn.net/softkexin/archive/2011/06/23/6562812.aspx


相关阅读:
Top