What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleRotate the points in a polygon
Keywordsrotate, polygon, point

When you rotate a point (X, Y) around the origin through angle theta, the point's new coordinates (X', Y') are given by:

    X' = Cos(theta) * X - Sin(theta) * Y
    Y' = Sin(theta) * X + Cos(theta) * Y

To rotate around a point other than the origin, translate the point so the point of rotation is at the origin, rotate, and then translate back.

This example starts with a square centers at the origin. For several angles, the program rotates the square's points, translates to center the square on the form, and draws the rotated/translated square.

Private Sub Form_Load()
Const PI As Single = 3.14159265

Dim orig_pts(1 To 4) As POINTAPI
Dim pts(1 To 4) As POINTAPI
Dim theta As Single
Dim dtheta As Single
Dim cx As Single
Dim cy As Single
Dim i As Integer
Dim p As Integer
Dim new_x As Single
Dim new_y As Single

    ScaleMode = vbPixels

    ' Define the rectangle centered at the origin.
    orig_pts(1).x = -ScaleWidth * 0.3
    orig_pts(2).x = -orig_pts(1).x
    orig_pts(3).x = orig_pts(2).x
    orig_pts(4).x = orig_pts(1).x

    orig_pts(1).y = orig_pts(1).x
    orig_pts(2).y = orig_pts(1).y
    orig_pts(3).y = -orig_pts(1).y
    orig_pts(4).y = orig_pts(3).y

    ' Find the center of the form.
    cx = ScaleWidth / 2
    cy = ScaleHeight / 2

    DrawWidth = 2

    theta = 0
    dtheta = PI / 8
    For i = 1 To 4
        ' Rotate by angle theta.
        For p = 1 To 4
            With orig_pts(p)
                ' Rotate around the origin.
                new_x = Cos(theta) * .x - Sin(theta) * .y
                new_y = Sin(theta) * .x + Cos(theta) * .y
            End With
            With pts(p)
                ' Center the rectangle.
                .x = new_x + cx
                .y = new_y + cy
            End With
        Next p

        ' Draw the rotated rectangle.
        ForeColor = QBColor(i)
        Polygon hdc, pts(1), 4

        theta = theta + dtheta
    Next i
End Sub
For more information on graphics programming in Visual Basic, see my book Visual Basic Graphics Programming.
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.