Draw a rotating rectangle.

Posted on 2005-05-10
Last Modified: 2013-12-26
I have a VB.NET program that draws a triangle every 'tick'  from some given info.  This code was adapted from some VB6 code on Lucky's VB site from a tutorial called CarAI.  Here is the VB.NET code:
Dim intX1 As Integer    'Coordinates of the 3 triangle verticies
Dim intY1 As Integer
Dim intX2 As Integer
Dim intY2 As Integer
Dim intX3 As Integer
Dim intY3 As Integer
Dim p As New Pen(Color.Blue, 1)

intX1 = Location_X + Radius * Math.Sin(Direction)
intY1 = Location_Y - Radius * Math.Cos(Direction)
intX2 = Location_X + Radius * Math.Sin(Direction + 2 * PI / 3)
intY2 = Location_Y - Radius * Math.Cos(Direction + 2 * PI / 3)
intX3 = Location_X + Radius * Math.Sin(Direction + 4 * PI / 3)
intY3 = Location_Y - Radius * Math.Cos(Direction + 4 * PI / 3)

g.DrawLine(p, intX1, intY1, intX2, intY2)
g.DrawLine(p, intX2, intY2, intX3, intY3)
g.DrawLine(p, intX3, intY3, intX1, intY1)

I believe radius just changes the size of the triangle.

My question is, how do I modify this code to draw 4 lines making up a rectangle(instead of a triangle) of a given length and width?  I do not understand this math very well and really have no idea how to do it.  

Thank you

Question by:nexguy
    LVL 4

    Accepted Solution

    You only have to change the above code a little to draw any multi-sided, equilateral polygons.

    Const POLYGONSIDES As Integer = 4  ' change number of sides for your polygon

    Private Sub PictureBox1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles PictureBox1.Paint
            Dim g As Graphics
            Dim myPts() As Point  ' create an array of points
            Dim SideAngle As Single
            Dim X, Y, i As Integer
            Dim p As New Pen(Color.Blue, 1)

            ReDim myPts(POLYGONSIDES - 1)
            SideAngle = 2 * Math.PI / POLYGONSIDES
            For i = 0 To POLYGONSIDES - 1
                X = Location_X + Radius * Math.Sin(Direction + i * SideAngle)
                Y = Location_Y - Radius * Math.Cos(Direction + i * SideAngle)
                myPts(i) = New Point(X, Y)
            Next i
            g = e.Graphics
            g.DrawPolygon(p, myPts)
        End Sub

    The SideAngle variable in the previous example represents the angle within a cirle that represents the chord created by one side.  The SideAngle is calculated by taking the radian angles for a circle (2*PI) and dividing it by the number of sides.  Radius holds the length of the radius of the circle in which the polygon is inscribed.  The Direction variable represents the base angle for the first point on the polygon.  The subsequent points are found by adding a multiple of the unit angle (SideAngle).

    Drawing a rectangle of varying width and height is going to be a little more complicated than the equilateral triangle.

    The following code is from a rectangle class that I created.  To draw the rectangle, I first find the center by dividing Width and Height by 2.

        Public Sub DrawRect(ByVal g As Graphics)
            Dim RectPts(3) As Point
            Dim Theta As Single
            Dim HalfWid, HalfHgt As Integer

            HalfWid = Width / 2
            HalfHgt = Height / 2
            Rad = Math.Sqrt(HalfWid * HalfWid + HalfHgt * HalfHgt)

            Theta = Math.Acos(HalfWid / Rad)
            RectPts(0) = GetPt(Theta)
            RectPts(1) = GetPt(Math.PI - Theta)
            RectPts(2) = GetPt(Math.PI + Theta)
            RectPts(3) = GetPt(-Theta)
            g.DrawPolygon(PenColor, RectPts)
        End Sub

        Private Function GetPt(ByVal Offset As Single) As Point
            Dim tAngle As Single

            tAngle = Rotation / 180 * Math.PI + Offset
            GetPt.X = CenterX + Rad * Math.Cos(tAngle)
            GetPt.Y = CenterY + Rad * Math.Sin(tAngle)
        End Function

    Excuse me.  Gotta be somewhere else now.  Will catch up with the explanation later.
    LVL 4

    Expert Comment

    Trig Review
    To find the X and Y components of a point on a circle, we use the following formulas:
    X = LengthOfRadius*Cosine(Theta)
    Y = LengthOfRadius*Sine(Theta)
    where Theta is is the angle formed by the positive X axis and the radius intersecting with the desired point on the circle.

    The Rad variable represents the distance (radius) from the center of the rectangle to a corner which coincides with a point on the circle in which the rectangle is inscribed.  We find this length by using the Pythagorean theorem (squareroot of (a^2 + b^2)).   We want to find the angle (Theta in radians) created by this radius and the positive X axis so we use the Acos function.  If we have the trig. formula

    X = LengthOfRadius*Cosine(Theta) -> X/LengthOfRadius = Cosine(Theta)

    then to find the angle Theta, we take the arccosine of X/LengthOfRadiu.  Once we have our angle, then we can find the points of the rectangle on the circle. Starting from the positive X axis and going counter-clockwise on our circle,  the first point would be at angle Theta.  The next point is at the halfway (pi radians) point of the circle minus the angle. The 3rd point is halfway point again plus the angle.  The last point starts from the X axis again but goes in the clockwise (negative) direction for the angle.
    The function GetPt receives these angles as a parameter that it uses to create the Point object.  The first part for the calculation of tAngle is just the conversion of the base rotation angle from degrees to radians:

    Rotation/360 * 2*PI -> Rotation/180*PI

    The offset is the radian angles that we add to the base angle calculated in the above formula.  To find the 4 points of the rectangle, we add the X and Y components to the centerpoint of the rectangle.
    LVL 4

    Expert Comment

    Word of caution:
    The coordinate system of many computer graphics has the positive Y axis going down instead of up as in the Cartesian coord. system.  The above code and examples was based on the Cartesian but still look all right since the rectangle is symmetric with respect to the major axes.  But for other graphics manipulation using trig functions, be sure to take the direction of the Y axis into account or else your drawings will appear upside-down.

    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Join & Write a Comment

    Suggested Solutions

    What is RenderMan: RenderMan is a not any particular piece of software. RenderMan is an industry standard, defining set of rules that any rendering software should use, to be RenderMan-compliant. Pixar's RenderMan is a flagship implementation of …
    As game developers, we quickly learn that Artificial Intelligence (AI) doesn’t need to be so tough.  To reference Space Ghost: “Moltar, I have a giant brain that is able to reduce any complex machine into a simple yes or no answer. (http://www.youtu…
    This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor ( If you're looking for how to monitor bandwidth using netflow or packet s…
    In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor ( If you're interested in additional methods for monitoring bandwidt…

    745 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    14 Experts available now in Live!

    Get 1:1 Help Now