TranformRotate About a point

ell

Member
Joined
May 26, 2009
Messages
8
Programming Experience
Beginner
I have figured out how to rotate graphics but I need a way of rotating graphics about a certain point, I have thought of rotating and then transforming but I'm not sure about how I would figure out where to transform to. I would be very greatfull if someone could provide a sub/function for doing this. Thanks in advance ell.
 
The RotateTransform method rotates about the origin of the Graphics object's coordinate system, which is the upper-left corner of the control or image being drawn on by default. If you want to rotate around a point other than the upper-left corner then you need to call TranslateTransform first, to shift the origin to the point you want to rotate around, and then call TranslateTransform. Just note that you need to take the translation into account when specifying the location of your drawing. As an example, try the following:

1. Create a new WinForms project.
2. Add a Timer to your form.
3. Add the following code:
VB.NET:
'The angle of rotation.
Private angle As Integer = 0

'The image to display.
Private image As Image = image.FromFile("put image file path here")

'Half the image's width.
Private halfImageWidth As Integer = image.Width \ 2

'Half the image's height.
Private halfImageHeight As Integer = image.Height \ 2

Private Sub Form1_Load(ByVal sender As Object, _
                       ByVal e As EventArgs) Handles MyBase.Load
    'Start the timer ticking 20 times per second.
    Me.Timer1.Interval = 50
    Me.Timer1.Start()
End Sub

Private Sub Timer1_Tick(ByVal sender As Object, _
                        ByVal e As EventArgs) Handles Timer1.Tick
    'Rotate one more degree clockwise and redraw the image.
    Me.angle = (Me.angle + 1) Mod 360
    Me.Refresh()
End Sub

Private Sub Form1_Paint(ByVal sender As Object, _
                        ByVal e As PaintEventArgs) Handles Me.Paint
    Dim clientSize As Size = Me.ClientSize

    With e.Graphics
        'Shift the Graphics object's origin to the centre of the form.
        .TranslateTransform(clientSize.Width \ 2, clientSize.Height \ 2)

        'Rotate the Graphics object's world around its origin.
        .RotateTransform(Me.angle)

        'Draw the image with its centre at the Graphics object's origin.
        .DrawImage(Me.image, -Me.halfImageWidth, -Me.halfImageHeight)
    End With
End Sub
4. Replace the image path place holder with the path of an actual image file on your system. Make it a relatively small image for best effect.
5. Run the project and drag the form to different sizes.

As you can see, the image is always drawn in the centre of the form and it is rotated around that centre.
 
Back
Top