我使用Adorner
类为我的控件创建旋转滑块。这是班级的相关部分:
Private initialAngle As Double
Private startVector As Vector
Private currentPoint, centerPoint As Point
Private rotateTransform As RotateTransform
Private RotateThumb As Thumb
Public Sub New(adornedElement As UIElement)
MyBase.New(adornedElement)
AddHandler RotateThumb.DragStarted, AddressOf HandleRotateStart
AddHandler RotateThumb.DragDelta, AddressOf HandleRotate
End Sub
Private Sub HandleRotateStart(sender As Object, e As DragStartedEventArgs)
Dim AE As FrameworkElement = TryCast(Me.AdornedElement, FrameworkElement)
centerPoint = New Point(AE.Width / 2, AE.Height / 2)
Dim startPoint As Point = Mouse.GetPosition(AE.Parent)
startVector = Point.Subtract(centerPoint, startPoint)
rotateTransform = TryCast(AE.RenderTransform, RotateTransform)
If rotateTransform Is Nothing Then
AE.RenderTransform = New RotateTransform(0, centerPoint.X, centerPoint.Y)
initialAngle = 0
Else
initialAngle = rotateTransform.Angle
End If
End Sub
Private Sub HandleRotate(sender As Object, e As DragDeltaEventArgs)
Dim AE As FrameworkElement = TryCast(Me.AdornedElement, FrameworkElement)
currentPoint = Mouse.GetPosition(AE.Parent)
Dim deltaVector As Vector = Point.Subtract(centerPoint, currentPoint)
Dim angle As Double = Vector.AngleBetween(deltaVector, startVector)
Dim myrotateTransform = TryCast(AE.RenderTransform, RotateTransform)
myrotateTransform.Angle = initialAngle + Math.Round(angle, 0)
AE.InvalidateMeasure()
End Sub
Protected Overrides Sub OnRender(drawingContext As DrawingContext)
MyBase.OnRender(drawingContext)
If Mouse.LeftButton = MouseButtonState.Pressed Then
drawingContext.DrawEllipse(New SolidColorBrush(Color.FromArgb(100, 0, 255, 0)), New Pen(Brushes.Green, 1), centerPoint, 10, 10)
drawingContext.DrawEllipse(New SolidColorBrush(Color.FromArgb(100, 255, 0, 0)), New Pen(Brushes.Red, 1), currentPoint, 7, 7)
End If
End Sub
虽然这样做(有点)旋转元素,问题是currentPoint
似乎不是我的鼠标指针所在的位置(OnRender
的红色椭圆不跟随鼠标正确)。我怀疑这可能与RenderTransform
有关,我应用于影响DrawingContext
的元素。或者它是关于我在这里做的数学?