Results 1 to 9 of 9

Thread: [RESOLVED] 2D translate + scale + rotate

Threaded View

  1. #1

    Thread Starter
    PowerPoster boops boops's Avatar
    Join Date
    Nov 2008
    Location
    Holland/France
    Posts
    3,201

    Resolved [RESOLVED] 2D translate + scale + rotate

    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:

    vb.net Code:
    1. Private Sub ZoomToPoint(zoomRatio As Double, zoomFocus As Point, rotation As Double)
    2.  
    3.     'Scale the image around the image origin:
    4.     _ZoomFactor *= zoomRatio
    5.     _Image.Width = sourceWidth * _ZoomFactor
    6.     _Image.Height = sourceHeight * _ZoomFactor
    7.  
    8.     'Calculate how far the image point which was under the zoom focus has shifted:
    9.     Dim imageX As Double = Canvas.GetLeft(_Image)
    10.     Dim imageY As Double = Canvas.GetTop(_Image)
    11.     Dim shiftX As Double = (zoomFocus.X - imageX) * (zoomRatio - 1)
    12.     Dim shiftY As Double = (zoomFocus.Y - imageY) * (zoomRatio - 1)
    13.  
    14.     'Modify the shift values to allow for rotation:
    15.         Dim cos = Math.Cos(rotation * Math.PI / 180)
    16.     Dim sin = Math.Sin(rotation * Math.PI / 180)
    17.     Dim shiftRX As Double = cos * shiftX - sin * shiftY
    18.     Dim shiftRY As Double = sin * shiftX + cos * shiftY
    19.  
    20.     'Translate the image to cancel the shift:
    21.     Canvas.SetLeft(_Image, Canvas.GetLeft(_Image) - shiftRX)
    22.     Canvas.SetTop(_Image, Canvas.GetTop(_Image) - shiftRY)
    23. End Sub
    24.  
    25. 'rotation is performed separately:
    26.     _Image.RenderTransform = New RotateTransform(_Rotation, _Image.Width / 2, _Image.Height / 2)
    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.

    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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width