My ZoomPictureBox (see sig) provides image dragging and zooming, with zooming around an arbitrary point such as the mouse position. I'm now trying to do something similar in WPF, but with image rotation too. Unfortunately my school-trig/back-of-envelope mathematical skills are letting me down. Here's the code I'm using, which I hope will be reasonably self-explanatory:
Rotation is always around the centre of the image. The above code works fine when the rotation is 0 or when the zoom focus is also at the centre of the image. But when the zoom focus is at some other position (e.g. the mouse position) the rotated image wanders off during zooming. I suspect that my rotation code (lines 15-18) needs some additional correcting factor but I can't figure it out.vb.net Code:
Private Sub ZoomToPoint(zoomRatio As Double, zoomFocus As Point, rotation As Double) 'Scale the image around the image origin: _ZoomFactor *= zoomRatio _Image.Width = sourceWidth * _ZoomFactor _Image.Height = sourceHeight * _ZoomFactor 'Calculate how far the image point which was under the zoom focus has shifted: Dim imageX As Double = Canvas.GetLeft(_Image) Dim imageY As Double = Canvas.GetTop(_Image) Dim shiftX As Double = (zoomFocus.X - imageX) * (zoomRatio - 1) Dim shiftY As Double = (zoomFocus.Y - imageY) * (zoomRatio - 1) 'Modify the shift values to allow for rotation: Dim cos = Math.Cos(rotation * Math.PI / 180) Dim sin = Math.Sin(rotation * Math.PI / 180) Dim shiftRX As Double = cos * shiftX - sin * shiftY Dim shiftRY As Double = sin * shiftX + cos * shiftY 'Translate the image to cancel the shift: Canvas.SetLeft(_Image, Canvas.GetLeft(_Image) - shiftRX) Canvas.SetTop(_Image, Canvas.GetTop(_Image) - shiftRY) End Sub 'rotation is performed separately: _Image.RenderTransform = New RotateTransform(_Rotation, _Image.Width / 2, _Image.Height / 2)
I realize that the "right" way to do this would be to use vectors and transformation matrices for everything, but my mathematical knowledge gets really hazy there. Still, if anyone wants to recommend a solution on those lines, I'll be glad to hear of it.
BB




Reply With Quote