I'm using Adorner
class to create a rotation thumb for my controls. Here's the relevant part of the class:
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
While this does (kind of) rotate the element, the problem is that currentPoint
does not appear to be where my mouse pointer is (the red ellipse of OnRender
doesn't follow mouse correctly). I suspect this might have something to with RenderTransform
that I apply on my element affecting DrawingContext
. Or is it about the mathematics I'm doing here?