如何在WPF中在不同大小的运行时绘制矩形和直线

时间:2019-04-02 13:22:47

标签: wpf vb.net

我在网上查看了很多示例,但没有发现与我的问题有关的任何内容。如果这是另一个问题的重复,我深表歉意。 我有一个带有按钮的XAML文件,可以绘制圆形和矩形,但是它们绘制的形状是固定大小的。我希望用户能够自由绘制(更改高度和宽度)矩形,直线和圆。

这是我的XAML代码:

<DockPanel>
    <ToggleButton DockPanel.Dock="Top" Name="CreateShape1" Click="CreateShape1_Click" Content="Create Rectangle" Margin="333,0,48,0" Height="23" />
    <ToggleButton DockPanel.Dock="Top" Name="CreateShape2" Click="CreateShape2_Click" Content="Create Circle" Margin="333,0,48,0" Height="21" />
    <Canvas Background="LightGray" Name="canvasArea"
            MouseLeftButtonDown="canvasArea_MouseLeftButtonDown" 
            MouseRightButtonDown="canvasArea_MouseRightButtonDown">
    </Canvas>
</DockPanel>

下面是背后的代码:

 Private Sub CreateShape1_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    Shape1 = SelectedShape.Rectangle
End Sub

Private Sub CreateShape2_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    Shape1 = SelectedShape.Circle
End Sub

Private Sub canvasArea_MouseLeftButtonDown(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
    Dim Rendershape As Shape = Nothing

    Select Case Shape1
        Case SelectedShape.Circle
            Rendershape = New Ellipse() With {
                    .Height = 40,
                    .Width = 40
                }
            Dim brush As RadialGradientBrush = New RadialGradientBrush()
            brush.GradientStops.Add(New GradientStop(CType(ColorConverter.ConvertFromString("#FF7689"), Color), 0.25))
            brush.GradientStops.Add(New GradientStop(CType(ColorConverter.ConvertFromString("#FF7689"), Color), 0.1))
            brush.GradientStops.Add(New GradientStop(CType(ColorConverter.ConvertFromString("#FF7689"), Color), 8))
            Rendershape.Fill = brush
        Case SelectedShape.Rectangle
            Rendershape = New Rectangle() With {
                                    .Stroke = Brushes.Black,
                                    .Opacity = 0.9,
                                    .Height = 45,
                                    .Width = 95,

                                    .RadiusX = 12,
                                    .RadiusY = 12
                                    }
        Case Else
            Return

    End Select

    Canvas.SetLeft(Rendershape, e.GetPosition(canvasArea).X)
    Canvas.SetTop(Rendershape, e.GetPosition(canvasArea).Y)
    canvasArea.Children.Add(Rendershape)
End Sub

这是现在的形状: Current shapes

谢谢!

0 个答案:

没有答案